chomp in perl not working as expected

前端 未结 4 1734
逝去的感伤
逝去的感伤 2021-01-14 06:33

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

<         


        
4条回答
  •  情话喂你
    2021-01-14 07:02

    Generally, you can use s,$/$,,r regex as a non-destructive chomp. It removes record separator $/ from the end of $_ or the string provided using =~, and returns the result without modifying anything. Your example would look like this:

    if ( $str1 =~ s,$/$,,r eq $str2 =~ s,$/$,,r )
    

    More formally the regex should be s,\Q$/\E$,,r, so $/ is not treated as regex. In paragraph mode the regex would need to be s,\n*$,,r. In slurp or fixed record mode the regex is not needed at all (chomp does nothing).

提交回复
热议问题