Perl chop

Perl chop() shouldn't be easily confused with a pork chop, but there could be a mixup with another, more popular, Perl function: chomp(). The latter is used to remove the string terminator (usually a backslash-n) from the string itself, while chop() is less selective, and removes the last character from a string, whatever it is.

We usually pass a scalar to the chop() function, and usually it is a string. The function returns the last string character (or ASCII NUL, the backslash-zero character, if there is nothing to chop in the string) and it has the side effect of removing that last character from the string itself.

Here is a short example:

my $countdown = "0123456789";
while(1)
{
my $current = chop($countdown);
last if(ord($current) == 0);

print "$current\n";
}

In an infinite loop we iteratively chop a string ouputting the chopped character. If the returned value from chop() is the NUL character we terminate the loop, otherwise we print it on a dedicated line.

No comments:

Post a Comment