in reply to Assigning the result of a chomp to the chomped var itself.

I have a behavior that is even more difficult to understand (running Perl 5.14.4).

Running the test directly under the Perl debugger:

DB<1> $x = "a\n"; DB<2> $x = chomp $x; DB<3> print $x 1
And running the same at the command line:
$ perl -E 'my $x = "a\n"; $x = chomp $x; say $x' 0
So I get 1 under the debugger et 0 at the command line. Isn't it strange?

And, BTW, using another variable solves the issue:

$ perl -E 'my $x = "a\n"; my $y = chomp $x; say $y;' 1
This leads me to believe that doing this:
$x = chomp $x;
might well be undefined behavior (and should most probably be avoided), just as:
$c = ++$c;
is undefined both in C and in Perl. (And different C compilers actually give different results on the code above, I have tried it once in the past.)

Replies are listed 'Best First'.
Re^2: Assigning the result of a chomp to the chomped var itself.
by Anonymous Monk on Nov 26, 2014 at 20:02 UTC

    Interesting...

    $ perl -wMstrict -e 'my $x = "a\n"; $x = chomp $x; print "<$x>\n"' <0> $ perl -wMstrict -e 'our $x = "a\n"; $x = chomp $x; print "<$x>\n"' <1> $ perl -wMstrict -MO=Terse -e 'our $x; $x = chomp $x;' LISTOP (0x8aa33b8) leave [1] OP (0x8aa3694) enter COP (0x8aa33dc) nextstate UNOP (0x8aa3414) null [15] SVOP (0x8aa3434) gvsv GV (0x8a9e5c0) *x COP (0x8aa36b8) nextstate BINOP (0x8aa36f0) sassign UNOP (0x8aa3714) schomp [2] UNOP (0x8aa3750) null [149] UNOP (0x8aa3774) null [15] SVOP (0x8aa3794) gvsv GV (0x8a9e5c0) *x UNOP (0x8aa3368) null [15] SVOP (0x8aa3398) gvsv GV (0x8a9e5c0) *x $ perl -wMstrict -MO=Terse -e 'my $x; $x = chomp $x;' LISTOP (0x92913d8) leave [1] OP (0x9291754) enter COP (0x92913fc) nextstate OP (0x9291434) padsv [1] COP (0x929171c) nextstate UNOP (0x9291778) schomp [1] UNOP (0x9291368) null [149] OP (0x92913a0) padsv [1]