in reply to Strange aliasing(?) when modifying variable in range operator
You are reading and modifying the same variable in the same expression where order of operand evaluation is not provided. As such, the result is undefined.
That said, for all existing versions of Perl, you'll get the same results, so we can explain what happens even if you can't count on it.
The key to understanding what happens is that $i puts $i on the stack. Not a copy of it, but $i itself. So $i..($i+=3)-1 is equivalent to $i+3 .. ($i+=3)-1, which will always be an empty range.
The following recreates the issue. If you add debug statements, you'll see range receiving arguments 7 and 6.
use feature qw( say refaliasing ); no warnings qw( experimental::refaliasing ); my @stack; sub padsv { \$stack[@stack] = \$_[0]; } sub const { \$stack[@stack] = \$_[0]; } sub add_equal { \my $rhs = \pop(@stack); \my $lhs = \pop(@stack); \my $rv = \( $lhs += $rhs ); \$stack[@stack] = \$rv } sub add { \my $rhs = \pop(@stack); \my $lhs = \pop(@stack); \my $rv = \( $lhs + $rhs ); \$stack[@stack] = \$rv } sub minus { \my $rhs = \pop(@stack); \my $lhs = \pop(@stack); \my $rv = \( $lhs - $rhs ); \$stack[@stack] = \$rv } sub range { \my $rhs = \pop(@stack); \my $lhs = \pop(@stack); #say "$lhs..$rhs"; \$stack[@stack] = \$_ for $lhs .. $rhs; } my $i = 4; # $i @stack # -- ------- padsv($i); # 4 $i padsv($i); # 4 $i,$i const(3); # 4 $i,$i,3 add_equal(); # 7 $i,7 const(1); # 7 $i,7,1 minus(); # 7 $i,6 range(); # 7 - say join ', ', @stack; # ""
In comparison, $i+0 .. ($i+=3)-1:
my $i = 4; # $i @stack # -- ------- padsv($i); # 4 $i const(0); # 4 $i,0 add(); # 4 4 padsv($i); # 4 4,$i const(3); # 4 4,$i,3 plus_equal(); # 7 4,7 const(1); # 7 4,7,1 minus(); # 7 4,6 range(); # 7 4,5,6 say join ', ', @stack; # "4, 5, 6"
|
|---|