Perl array unshift() function - Quick Tutorial

How to use the array unshift() function

Woman Using Laptop in Kitchen
Fuse/Getty Images
 $TOTAL = unshift(@ARRAY, VALUES); 
Perl's unshift() function is used to add a 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.
 @myNames = ('Curly', 'Moe');
 unshift(@myNames, 'Larry'); 
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 of 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.

 @myNames = (
 unshift(@myNames, 'Larry'); 
You can unshift() multiple values onto the array directly:
 @myNames = ('Moe', 'Shemp');
 unshift(@myNames, ('Larry', 'Curly')); 
Or by unshift()-ing an array:
 @myNames = ('Moe', 'Shemp');
 @moreNames = ('Larry', 'Curly');
 unshift(@myNames, @moreNames);