Perl:postfix/prefix 优先级哪里出错了?
Perl: Where am I going wrong with postfix/prefix precedence?
以下片段显示了一个简单的 n-perline 输出过程。
在布尔表达式中显示了两种情况,一种使用前缀 ++,另一种使用后缀 ++。
由于“++”的优先级高于“==”,我希望结果相同,但结果不同:一个每行 5 个,另一个 6 个。
use English;
my @arr = (1,2,3,4,5,6,7,8,9,8,7,6);
my $perline = 5;
my $ndone = 0;
for(@arr) {
print " $ARG";
if(++$ndone == $perline) {
$ndone = 0;
print "\n";
}
}
print "\n---\n";
my $perline = 5;
my $ndone = 0;
for(@arr) {
print " $ARG";
if($ndone++ == $perline) {
$ndone = 0;
print "\n";
}
}
输出:
1 2 3 4 5
6 7 8 9 8
7 6
---
1 2 3 4 5 6
7 8 9 8 7 6
这不是关于操作的优先级,而是关于什么前缀和后缀++ return。来自 perldoc perlop:
"++" and "--" work as in C. That is, if placed before a variable, they
increment or decrement the variable by one before returning the value, and
if placed after, increment or decrement after returning the value.
基本上你可以将它们定义为函数:
sub prefix_plusplus {
$_[0] = $_[0] + 1; # increment value
return $_[0]; # returns value after increment
}
sub postfix_plusplus {
my $before = $_[0];
$_[0] = $_[0] + 1; # increment value
return $before; # returns value before increment
}
my $x = my $y = 5;
printf "%d,%d\n", prefix_plusplus($x), postfix_plusplus($y); # 6,5
printf "%d,%d\n", $x, $y; # 6,6
# and same thing with the ++ operand
$x = $y = 5;
printf "%d,%d\n", ++$x, $y++; # 6,5
printf "%d,%d\n", $x, $y; # 6,6
以下片段显示了一个简单的 n-perline 输出过程。
在布尔表达式中显示了两种情况,一种使用前缀 ++,另一种使用后缀 ++。
由于“++”的优先级高于“==”,我希望结果相同,但结果不同:一个每行 5 个,另一个 6 个。
use English;
my @arr = (1,2,3,4,5,6,7,8,9,8,7,6);
my $perline = 5;
my $ndone = 0;
for(@arr) {
print " $ARG";
if(++$ndone == $perline) {
$ndone = 0;
print "\n";
}
}
print "\n---\n";
my $perline = 5;
my $ndone = 0;
for(@arr) {
print " $ARG";
if($ndone++ == $perline) {
$ndone = 0;
print "\n";
}
}
输出:
1 2 3 4 5
6 7 8 9 8
7 6
---
1 2 3 4 5 6
7 8 9 8 7 6
这不是关于操作的优先级,而是关于什么前缀和后缀++ return。来自 perldoc perlop:
"++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable by one before returning the value, and if placed after, increment or decrement after returning the value.
基本上你可以将它们定义为函数:
sub prefix_plusplus {
$_[0] = $_[0] + 1; # increment value
return $_[0]; # returns value after increment
}
sub postfix_plusplus {
my $before = $_[0];
$_[0] = $_[0] + 1; # increment value
return $before; # returns value before increment
}
my $x = my $y = 5;
printf "%d,%d\n", prefix_plusplus($x), postfix_plusplus($y); # 6,5
printf "%d,%d\n", $x, $y; # 6,6
# and same thing with the ++ operand
$x = $y = 5;
printf "%d,%d\n", ++$x, $y++; # 6,5
printf "%d,%d\n", $x, $y; # 6,6