Main Content

Removing the new line with chop or chomp in Perl - what is the difference?

Archive - Originally posted on "The Horse's Mouth" - 2010-09-21 06:01:20 - Graham Ellis

Where Perl supports functions of similar names, you'll find they do similar things - such as chop v chomp.

chop always removes the last character of a string
  whereas
chomp removes the last character of a string but only if it is a new line

Both chop and chomp alter the variable that's passed in to them and they return result; in the case of chop, that's the character that was removed and in the case of chomp (since you'll already know the character), it's the number of characters removed.

Since functions like print, printf and sprintf all output the result of any other functions they call, using a chop or chomp directly with a one of them will result in a new line or a count being displayed / output, rather than a reduced version of the input string.

Sample program ... including sample outputs ... [here]




Notes

chomp will also work on a list, removing final new-line characters from each member of the list

• If you want to trim all the white spaces, as well as any new line character, off the end of a string, you can do it in a single operation using the s operator:
  $varname =~ s/\s+$//;
which (in literal terms) replaces one or more trailing white space characters - space, tab, new line and carriage return - with nothing.