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.)

In reply to Re: Assigning the result of a chomp to the chomped var itself. by Laurent_R
in thread Assigning the result of a chomp to the chomped var itself. by choroba

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.