Using the Perl chop() function

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:

This program gives you:

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).

This produces the output:

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:

This program outputs:

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

See also

Scroll to Top