Tweet

Using the Perl chop() function

Introduction

Sometimes you will find you want to unconditionally remove the last character from a string. While you can easily do this with regular expressions, chop is more efficient.

The chop() function will remove the last character of a string (or group of strings) regardless of what that character is. Note, if you want to easily remove newlines or line separators see the chomp() howto.

Example 1. Chopping a string

The chop() function removes and returns the last character from the given string:

  #!/usr/bin/perl
  use strict;
  use warnings;

  my $string = 'frog';

  my $chr = chop($string);

  print "String: $string\n";
  print "Char: $chr\n";

This program gives you:

  String: fro
  Char: g

If the string is empty, chop() will return an empty string. If the string is undefined, chop() will return undefined.

Example 2. Chopping strings in an array

If you pass the chop() function an array, it will remove the last character from every element in the array.

Note that this will only work for a one-dimensional array. In other words, it is not valid to pass in an array reference, or an array that contains an array (or hash).

  #!/usr/bin/perl
  use strict;
  use warnings;

  my @array = ('fred', 'bob', 'jill', 'joan');

  my $chr = chop(@array);

  foreach my $str (@array) {
    print "$str\n";
  }

  print "Char: $chr\n";

This produces the output:

  fre
  bo
  jil
  joa
  Char: n

Example 3. Chopping strings in a hash

If you pass a hash into chop(), it will remove the last character from the values (not the keys) in the hash. For example:

  #!/usr/bin/perl
  use strict;
  use warnings;

  my %hash = (
    first => 'one',
    second => 'two',
    third => 'three',
  );

  my $chr = chop(%hash);

  foreach my $k (keys %hash) {
    print "$k: $hash{$k}\n";
  }

  print "Char: $chr\n";

This program outputs:

  first: on
  second: tw
  third: thre
  Char: e

Note that as with arrays, chop is not designed to process hash reference or hashes containing other hashes (or arrays).

See also

  perldoc -f chop
  perldoc -f chomp
  chomp()
[Top]