Salvor has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

in a Perl training (I am the trainer) we discovered some odd(?) behavior of the chomp() function.

I know, of course, that it returns the number of removed line-ends, and so it does:

my $line = "hello\n"; my $x = chomp $line; print $x; # prints "1"
But to demonstrate wrong usage of chomp(), I tried
my $line = "hello\n"; $line = chomp $line; print $line; # prints "0"!

What am I missing here? Why doesn't it just overwrite the content of $line with "1"?

I tested it on Linux and Windows/ActivePerl with newer Perls (5.20 I think). Same behaviour.

Perhaps someone could enlighten me/us? Thanks in advance!

Replies are listed 'Best First'.
Re: Odd behaviour of chomp()
by dave_the_m (Monsignor) on Oct 20, 2015 at 10:58 UTC
    It's a bug that's been fixed in 5.22.0.

    From perl5220delta.pod:

    Assignment to a lexical scalar is often optimised away; for example in C<my $x; $x = $y + $z>, the assign operator is optimised away and the +add operator writes its result directly to C<$x>. Various bugs related to this optimisation have been fixed. Certain operators on the right-han +d side would sometimes fail to assign the value at all or assign the wro +ng value, or would call STORE twice or not at all on tied variables. The operators affected were C<$foo++>, C<$foo-->, and C<-$foo> under C<use integer>, C<chomp>, C<chr> and C<setpgrp>.

    Dave.

A reply falls below the community's threshold of quality. You may see it by logging in.