Using the Perl push() function
Introduction
You can use the push
function to add new elements to the end of an array.
Example 1. Adding an item onto an array
You can use push
to push an element onto the end of an array:
This program produces the following output:
You can see that ‘jupiter’ is now on the end of our @planets
array.
The push
function returns the number of elements in the array after the new value(s) have been appended. If we wanted to see how many planets were in the modified @planets
array, we could change our code as follows:
The output is now:
Example 2. Joining two arrays together
You can also use push
to append an array onto the end of another array:
As the following output demonstrates, the @outer_planets
array has been added to the end of the @planets
array:
Example 3. Adding to an array reference
You can use push
to append elements onto the end of a reference to an array, but you must dereference it first:
This produces the following output: