chomp in perl not working as expected

时间秒杀一切 提交于 2019-12-19 09:49:38

问题


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?


回答1:


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.



回答2:


chomp returns the number of characters removed, not the strings that have been chomped.




回答3:


I like the name chomp() it's sound tells you what it does. As @ruakh mentions it takes one or more arguments, so you can say:

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

You can also hand it an array of strings, like what you would get from reading a whole file at once, e.g.:

chomp(@lines);



回答4:


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



来源:https://stackoverflow.com/questions/9270915/chomp-in-perl-not-working-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!