Perl Programming/Keywords/chop

Previous: chomp Keywords Next: chown

The chop keyword

edit

The chop function chops off the last character of a string and returns it. It is much more efficient than s/.$//s, as it neither scans nor copies the string. Without VARIABLE, it chops $_. If VARIABLE is a hash, it chops the hash's values, not its keys, and resets the each iterator in the process.

If a list is chopped, each element is chopped off, but only the value of the last chop is returned. Note that chop returns the last character. To return all but the last character, substr($string, 0, -1) should be used.

Syntax

edit
  chop VARIABLE
  chop(LIST)
  chop

Examples

edit
  The code
use 5.10.0;

%favorite = (joe => 'red', sam => 'blue', walter => 'black');

%list = %favorite;

say "%favorite = ";
foreach my $element (%favorite) {
  say $element;
}

say "Now, chopping...";
say chop(%favorite);

say "%favorite = ";
foreach my $element (%favorite) {
  say $element;
}
returns the following:
%favorite =
walter
black
joe
red
sam
blue
Now, chopping...
e
%favorite =
walter
blac
joe
re
sam
blu


Previous: chomp Keywords Next: chown