How to Use the Perl Array Pop() Function

Illustration of computer programming

elenabs/Getty Images

When writing a Perl script you might find it handy to use the pop() function, which looks like this:

Perl's pop() function is used to remove and return (or pop) the last element from an array, which reduces the number of elements by one. The last element in the array is the one with the highest index. It's easy to confuse this function with shift(), which removes the first element from an array.

An Example of Using the Perl Pop() Function

If you think of an array as a row of numbered boxes, going from left to right, it would be the element on the far right. The pop() function would cut the element off the right side of the array, return it, and reduce the elements by one. In the examples, the value of $oneName becomes 'Moe', the last element, and @myNames is shortened to ('Larry', 'Curly').

The array can also be thought of as a stack—picture of a stack of numbered boxes, starting with 0 on the top, and increasing as it goes down. The pop() function would pop the element off the bottom of the stack, return it, and reduce the elements by one.