in reply to Re: When do you use chop instead of comp?
in thread When do you use chop instead of chomp?

    "chomp takes off any and all trailing newlines,..."

Nope. If there are multiple trailing newlines, chomp only removes one of them. That's the way it works unless you set $/ to an empty string, in which case it gobbles them all.

Consider:

my $str = "some string\n\n\n\n"; chomp $str; print "[$str]"; # still three trailing newlines $/ = ""; # 'paragraph mode' chomp $str; print "[$str]"; # all gone
Note also that while chomp does return the number of characters removed, that result may not be what you think if you are in Windows or Mac OS where \n gets written out as two characters. During the time that Perl still has the string in memory, the \n only counts as one character and the second chomp in the example above returns 3 (not 6) on my Windows machine -- just as it would on Linux.

On the other hand, if you assign a value to $/ that truly is more than one character (internally), that count gets returned as you would expect.

$/ = 'ggl'; # giggle mode my $str2 = "a string ggl"; my $cnt = chomp $str2; print "$cnt"; # prints: 3

------------------------------------------------------------
"Perl is a mess and that's good because the
problem space is also a mess.
" - Larry Wall

Replies are listed 'Best First'.
Re: Re: Re: When do you use chop insetad of comp?
by steves (Curate) on Mar 03, 2002 at 02:12 UTC

    Thanks. I re-read the docs. Somewhere early on I got the idea it removed all of them. Scary that I never had to check that until now.