in reply to chop vs chomp

chop takes off the last character of the string oblivious to what it is.
chomp takes off $/ ("\n" by default) if it exists as the last character, also known as the input record seperater

See perldoc -f chomp, vs perldoc -f chop for more information. chop returns what was taken off, chomp returns how many was taken off, (how many elements it effected). chomp is most often used when reading from <STDIN>.

perl -e'$_="foo\n*"; chop; chomp; print;' ## Removes the *, then removes the terminating $/ (\n), prints foo
perl -e'$_="foo\n*"; chomp; chop; print;' ## There is no terminating $/ (\n) chomp returns 0, chop removes *, prints foo\n


Evan Carroll
www.EvanCarroll.com

Replies are listed 'Best First'.
Re^2: chop vs chomp
by sauoq (Abbot) on Oct 30, 2005 at 23:16 UTC
    Both return what was taken off.

    No, chomp returns the number of characters that were removed. As $/ can be more than 1 character, this value is not always 0 or 1. Example:

    $ perl -le '$foo = "foo\r\n"; $/ = "\r\n"; print chomp $foo; print len +gth $foo' 2 3

    Update: I should also mention that, when called with a list, chomp will return the sum of all characters removed from all members of the list.

    -sauoq
    "My two cents aren't worth a dime.";