Perl Array unshift() Function Tutorial

Woman Using Laptop in Kitchen
Fuse/Getty Images

Perl's unshift() function is used to add value or values onto the beginning of an array (prepend), which increases the number of elements. The new values then become the first elements in the array. It returns the new total number of elements in the array. It's easy to confuse this function with push(), which adds elements to the end of an array.

Picture a row of numbered boxes, going from left to right. The unshift() function would add the new value or values on to the left side of the array, and increase the elements. In the examples, the value of @myNames becomes ('Larry', 'Curly', 'Moe').

The array can also be thought of as a stack—picture a stack of numbered boxes, starting with 0 on the top and increasing as it goes down. The unshift() function would add the value to the top of the stack, and increase the overall size of the stack.

You can unshift() multiple values onto the array directly:

Or by unshift()-ing an array: