Perl programming: chop and chomp

Continuing with Perl programming, the tutor discusses a couple of simple yet important functions: chop and chomp.

Back in my Nov 19 post, I mentioned the Perl function chop. In that case, chop was used to strip the newline off the end of a name the user had inputted from the keyboard.

The chop function will “chop” off the last character of a string. Here’s an example:

#!/usr/bin/perl
$stringvar=”You look pretty:)”;
print $stringvar;
print “\n\n”; #Prints two empty lines for easier reading.
chop $stringvar;
print $stringvar;

should give the output

You look pretty:)

You look pretty:

Notice that, with no newline at the end of the string, chop removes the mouth of the smiley. The chop function always removes the last character, whether you want it gone or not.

On the other hand, the chomp function (apparently) removes only unseen characters. Therefore, it will remove a newline from the end of a string, but not a letter, number, or punctuation. Observe:

#!/usr/bin/perl
$newstringvar=”I love your purse:) \n”;
$question=”Where did you get it?”;
print $newstringvar;
print $question;
chomp $newstringvar;
chomp $question;
print “\n\n”;#Prints two empty lines for easier reading.
print $newstringvar;
print $question;

should hopefully produce the output

I love your purse:)
Where did you get it?

I love your purse:) Where did you get it?

The chomp function benignly left the second string alone, since its end character is a question mark. From the first string chomp did remove the newline character (denoted by \n).

Believe it or not, there is even more about chop and chomp. Therefore, I’ll be saying more about them in future posts:)

Source:

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply