Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 of return works as expected:

foreach (@_) {
    return $sum += $_; # returns 1
}
like image 875
Grzegorz Szpetkowski Avatar asked Sep 02 '11 13:09

Grzegorz Szpetkowski


1 Answers

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.

like image 167
Eugene Yarmash Avatar answered Oct 05 '22 12:10

Eugene Yarmash