< Perl Programming < Keywords
![](../../../I/Crystal_Clear_action_apply.png.webp)
The code
The chop keyword
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
chop VARIABLE
chop(LIST)
chop
Examples
![](../../../I/Crystal_Clear_action_apply.png.webp)
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
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.