Perl Array Push() Function

Use the array push() function to add an element to an array

rear view of two programmers at a computer

Maskot/Getty Images

The Perl 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 the unshift() function, which adds elements to the beginning of an array. Here's an example of the Perl push() function:

@myNames = ('Larry', 'Curly');
push @myNames, 'Moe';
print "@myNames\n";

When this code is executed, it delivers:

Larry Curly Moe

Picture a row of numbered boxes, going from left to right. The push() function pushes the new value or values onto the right side of the array and increases the elements. 

The array can also be thought of as a stack. Picture a stack of numbered boxes, starting with 0 at the top and increasing as it goes down. The push() function pushes the value onto the bottom of the stack and increases the elements, like this:

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

You can also 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);

Note for beginning programmers: Perl arrays begin with an @ symbol. Each complete line of code must end with a semicolon. If it doesn't, it won't execute. In the stacked example in this article, the lines without a semicolon are values contained in an array and enclosed in parentheses. This isn't an exception to the semicolon rule, as much as a result of the stack approach. The values in the array are not individual lines of code. It is easier to picture this in the horizontal approach to coding.

Other Functions for Manipulating Arrays

Other functions are also used to manipulate arrays. These make it easy and efficient to use a Perl array as a stack or as a queue. In addition to the push function, you can use:

  • Pop function – removes and returns the last element of an array
  • Shift function – moves the whole array to the left. The element that is the first element of the array falls off the array and becomes the return value of the function
  • Unshift function – the opposite of the shift function, places a value at the beginning of an array and moves all the other element to the right.
Format
mla apa chicago
Your Citation
Brown, Kirk. "Perl Array Push() Function." ThoughtCo, Apr. 5, 2023, thoughtco.com/perl-array-push-function-quick-tutorial-2641151. Brown, Kirk. (2023, April 5). Perl Array Push() Function. Retrieved from https://www.thoughtco.com/perl-array-push-function-quick-tutorial-2641151 Brown, Kirk. "Perl Array Push() Function." ThoughtCo. https://www.thoughtco.com/perl-array-push-function-quick-tutorial-2641151 (accessed March 28, 2024).