xoombot has asked for the wisdom of the Perl Monks concerning the following question:

Whats the difference between chop and chomp?

Replies are listed 'Best First'.
Re: chop vs chomp
by pg (Canon) on Oct 30, 2005 at 23:23 UTC

    Try this demo:

    use strict; use warnings; { my $str = "0123456789"; for (1 .. 5) { chop $str; } print "[$str]"; } { my $str = "0123456789"; for (1 .. 5) { chomp $str; } print "[$str]"; } { my $str = "0123456789\n"; for (1 .. 5) { chop $str; } print "[$str]"; } { my $str = "0123456789\n"; for (1 .. 5) { chomp $str; } print "[$str]"; }

    It prints (observe it):

    [01234][0123456789][012345][0123456789]

    And read perlfunc.

Re: chop vs chomp
by EvanCarroll (Chaplain) on Oct 30, 2005 at 23:12 UTC
    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
      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.";