Once You Know, You Newegg

Perl Push function

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

@myNames = ('Larry', 'Curly');
push(@myNames, 'Moe');

Picture a row of numbered boxes, going from left to right. The push() function would push the new value or values on to the right 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 push() function would push the value into the bottom of the stack, and increase the elements.

@myNames = (
push(@myNames, 'Moe');

You can push multiple values onto the array directly:

@myNames = ('Larry', 'Curly');
push(@myNames, ('Moe', 'Shemp'));

Or by pushing on an array:

@myNames = ('Larry', 'Curly');
@moreNames = ('Moe', 'Shemp');
push(@myNames, @moreNames);

Comments are closed.