Perl chop() function

In the Perl programming language has a built-in function chop(). You can use this function when working with strings. In the simplest case, the function chop() removes the last character in a variable which is a passed argument in the function.

Here's an example:

▶ Run

my $string = 'ASDF';


print "'$string'";

This program displays the text 'ASD'.


If the function chop not given no arguments, the function works with default variable $_:

▶ Run

$_ = 123;


print "'$_'";

In that case if the variable $_ is undef and used use warnings;, will warning:

▶ Run

use strict;
use warnings;

Use of uninitialized value $_ in scalar chop at line 6.

In function chop() , you can pass scalars, arrays, hashes. In the case of the hash the feature will only work with values of keys, the keys themselves will not change.

The argument of the function chop() must always be variable. If to try to pass this function a string, it will error and program execution will be stopped:

▶ Run

chop('ASDF'); # Error!
Can't modify constant item in chop at line 3, near "'ASDF')"
Execution of aborted due to compilation errors.

Return value

Function chop() always returns a string. It can either be empty string '', or a string consisting of exactly one character.

Here is an example of a situation when chop() returns an empty string:

▶ Run

use Data::Dumper;

my $var = '';

warn Dumper chop($var);
warn Dumper $var;

Here is an example of a more frequent situation is when chop() returns a string of exactly one symbol. The function returns the character that was cut from the line:

▶ Run

use Data::Dumper;

my $var = 'asdf';

warn Dumper chop($var);
warn Dumper $var;

This program will display:

$VAR1 = 'f';
$VAR1 = 'asd';

Here is another example of a situation when chop() returns a single character.

▶ Run

use Data::Dumper;

my @arr = qw(abc def ghi);

warn Dumper chop(@arr);
warn Dumper \@arr;

The output of the program:

$VAR1 = 'i';
$VAR1 = [

Function chop() cut off the last character from all elements in the array, but returned the only character that was cut last.

Official documentation

Here is the output of the command perldoc -f chop:

       chop VARIABLE
       chop( LIST )
       chop    Chops off the last character of a string and returns the
               character chopped.  It is much more efficient than "s/.$//s"
               because it neither scans nor copies the string.  If VARIABLE is
               omitted, chops $_.  If VARIABLE is a hash, it chops the hash's
               values, but not its keys.

               You can actually chop anything that's an lvalue, including an

               If you chop a list, each element is chopped.  Only the value of
               the last "chop" is returned.

               Note that "chop" returns the last character.  To return all but
               the last character, use "substr($string, 0, -1)".

               See also "chomp".

Related topics

Other articles