Once we have created a list array, we can do much more than just access the elements.
We can also manipulate the elements in many ways.
In perl, list arrays are most often manipulated using the operators push, pop, shift and unshift.
push adds a new element on the right hand side of a list array.
The following code would create a list array of ("red", "green", "blue")
@colours = ("red", "green");
push (@colours, "blue");
In other words, the push operator, adds an element to the end of an existing list.
Pop does the exact same thing as push, but in reverse.
Pop extracts the right side element of a list array using the following syntax:
$popped_value = pop (@array_name);
We can pop out the value blue from @colours with the following syntax:
$last_colour = pop (@colours);
The @colours array now contains only "red" and "green" and the variable $last_color is equal to "blue".
Unshift does the exact same thing as push, but it performs the addition to the left side of the list array instead of to the right.
We would create the list ("blue", "red", "green") with the following syntax:
@colours = ("red", "green");
unshift (@colours, "blue");
Similarly, shift works the same as pop, but to the left side of the list array.
Thus, we reduce @colours to just "red" and "green" by shifting the first element blue with the
following syntax:
$first_colour = shift(@colours);
Thus, @colours again contains only "red" and "green" and $first_colour equals blue.
In addition to push, pop, shift, and unshift functions used, there others.
The following table summarises some of these.
| Operator | Description |
| shift(@array) | Removes the first element in @array |
| unshift (@array, $element) | Adds $element to the beginning of @array |
| pop (@array) | Removes the last element of @array |
| push (@array, $element) | Adds $element to the end of @array |
| @array=sort (@array) | Sorts the elements in @array |
| @array=reverse(@array) | Reverses the order of the elements in @array |
| chop(@array) | Chops off the last character of every element in @array |
| join (delimiter, @array) | Creates a scalar of every element in @array joined by the delimiter. |
Exercise
Create an array containing the following elements - fortran, c, visual basic, javascript.
Carry out each of the following steps in order then write down the resulting array