Returning value from foreach in subroutines
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 o开发者_StackOverflow中文版f return
works as expected:
foreach (@_) {
return $sum += $_; # returns 1
}
From perlsub:
If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while, the returned value is unspecified.
精彩评论