in reply to When do you use chop instead of chomp?

chop always takes off the last character of a string and returns that character.

chomp takes off any and all trailing newlines, but leaves the string alone if there are no newlines. It returns the number of characters removed. $/ determines what chomp thinks is a newline. So you can local that to remove newlines from files from other systems that have different newlines than your native OS.

  • Comment on Re: When do you use chop instead of comp?

Replies are listed 'Best First'.
Re: Re: When do you use chop insetad of comp?
by dvergin (Monsignor) on Mar 02, 2002 at 20:22 UTC
        "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

      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.