Search code examples
perlchomp

chomp in perl not working as expected


I found a strange behavior of chomp in Perl and I am unable to comprehend why is chomp is working like this.

The following line does not work as expected

if ( chomp($str1) eq chomp($str2) )

But, the following works fine

chomp $str1;
chomp $str2;
if ( $str1 eq $str2 )

Can you please give some insight in this behavior of chomp?


Solution

  • chomp modifies its argument. It does not return a modified argument. The second example is, in fact, how you're supposed to use it.

    edit: perldoc -f chomp says:

       chomp   This safer version of "chop" removes any trailing string that
               corresponds to the current value of $/ (also known as
               $INPUT_RECORD_SEPARATOR in the "English" module).  It returns
               the total number of characters removed from all its arguments.