Consider following simple example:
#!perl -w
use strict;
sub max {
my ($a, $b) = @_;
if ($a > $b) { $a }
else { $b }
}
sub total {
my $sum = 0;
foreach (@_) {
$sum += $_;
}
# $sum; # commented intentionally
}
print max(1, 5) . "\n"; # returns 5
print total(qw{ 1 3 5 7 9 }) . "\n";
According to Learning Perl (page 66):
“The last evaluated expression” really means the last expression that
Perl evaluates, rather than the last statement in the subroutine.
Can someone explain me why total doesn’t return 25 directly from foreach (just like if) ? I added additional $sum as:
foreach (@_) {
$sum += $_;
$sum;
}
and I have such warning message:
Useless use of private variable in void context at …
However explicit use of return works as expected:
foreach (@_) {
return $sum += $_; # returns 1
}
From perlsub: