Press "Enter" to skip to content

Differences between perl’s Chop & Chomp

Chop & Chomp

The chop function is used to “chop off” the last character of a string variable. It will remove that last character no matter what it is, so it should be used with caution. For example:

me
myself
you

If you had read the “me” line in and assigned it to a variable, say $who_am _I, the value you have for it should be:

men

Remembering /n is the same as a carriage return.

The chop command would look like this (assuming we assigned “men” to a variable named $who_am_I):

[code]
chop ($who_am_I);
[/code]

Using the chop function in this case will remove the n character. However, suppose we use it on the last of the three:

me
myself
you

The “you” is the last piece of text in the file, and could be missing the newline n character if it was, for instance, typed into the file manually and the “Enter” key was not pressed afterward. If the chop command is used in such a case, it will remove the “u”, which was not intended! So code such as:

[code]
chop ($who_are_you);
print “You are $who_are_you!”;
[/code]

This would result in the viewer seeing “You are yo!” rather than the expected result.

Now we look at the chomp function.

The chomp function will remove the last character of a string, but only if that character is an input record separator (the current value of $/ in Perl), which defaults to the newline (n) character. This is often used to remove the n character when reading from a file. The chomp function is much safer than the chop function for this, as it will not remove the last character if it is not n.

Now if we run the chomp command on that last line instead, it won’t remove the “u”.

[code]
chomp ($who_are_you);
print “You are $who_are_you!”;
[/code]

Now the viewer will see “You are you!” even if there was no n character at the end of the “you” line.

Simple enough, each having their own purpose in a given circumstance. Chomp being more common as it’s less likely to chop off bits you wanted.