Grz*_*ski 10 perl function return-value
考虑以下简单示例:
#!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";
Run Code Online (Sandbox Code Playgroud)
根据Learning Perl(第66页):
"最后计算的表达式"实际上是指Perl计算的最后一个表达式,而不是子例程中的最后一个语句.
有人可以解释一下为什么total不25直接返回foreach(就像if)?我添加了额外$sum的:
foreach (@_) {
$sum += $_;
$sum;
}
Run Code Online (Sandbox Code Playgroud)
我有这样的警告信息:
在void上下文中无用的私有变量...
但是return按预期显式使用作品:
foreach (@_) {
return $sum += $_; # returns 1
}
Run Code Online (Sandbox Code Playgroud)