arrays - Perl 语法组合 `foreach` 和 `if` : Shouldn't it work, 即 : Why doesn't it work?

标签 arrays perl for-loop syntax max

尝试在不能包含负数的数组中获取最大值我试过:

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/

相关文章:

java - for循环遍历java中的偶数

javascript - 尝试将这个大的 if else 语句转换为循环

c++ - 3D 阵列取消分配会导致段错误

ruby - Array.first 与 Ruby 中的 Array.shift

perl - 如何将 PERLBREW_ROOT 移动到另一个目录?

mysql - Bugzilla 安装 usr/bin/perl install-module.pl DBD::mysql 时出错

c - FOR 循环中的字符串

arrays - 迭代变体数组

.net - F#中的数组协方差

perl - 如何使用 Perl TK 将滚动条添加到主窗口