尝试在不能包含负数的数组中获取最大值我试过:
my @v;
#...
my $max = 0;
$max = $_
if ($_ > $max)
foreach (@v);
我收到 perl 5.18.2 的语法错误。
然而 (1) statement($_) foreach (@v);
和 (2) $max = $_ if ($_ > $max);
都很好,他们做了他们应该做的事。
那么如果 (1) 和 (2) 都是有效的陈述,为什么不能将它们组合在用于 (1) 的模式中?
只是没有人需要建议;这是我使用不同语法解决问题的方法:
foreach (@v) {
$max = $_
if ($_ > $max);
}
最佳答案
So if (1) and (2) are both valid statements, why can't they be combined in the pattern used for (1)?
您在这里使用的后缀语法(又名语句修饰符)不支持这种语句。
documentation says (强调我的):
Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending).
至于您的任务本身:从数组中获取最大值是一个非常常见的要求。一种简单而标准的方法是使用 function max()
from core module List::Util
:
use List::Util qw/max/;
my @v;
my $max = max 0, @v;
关于arrays - Perl 语法组合 `foreach` 和 `if` : Shouldn't it work, 即 : Why doesn't it work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63169959/