introduction to web programming Advanced list array manipulation with the push, pop, shift, and unshift functions Of course, 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 CGI, list arrays are most often manipulated using the operators push, pop, shift and unshift.

Push is used to add a new element on the right hand side of a list array. Thus, the following code would create a list array of ("red", "green", "blue")

    @colors = ("red", "green");
    push (@colors, "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);

Thus, we might pop out the value blue from @colors with the following syntax:

    $last_color_in_list = pop (@colors);

Thus, the @colors array now contains only "red" and "green" and the variable $last_color_in_list 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. Thus, we would create the list ("blue", "red", "green") with the following syntax:

    @colors = ("red", "green");
    unshift (@colors, "blue");

Similarly, shift works the same as pop, but to the left side of the list array. Thus, we reduce @colors to just "red" and "green" by shifting the first element blue with the following syntax:

     $first_color_in_list = shift(@colors);

Thus, @colors again contains only "red" and "green" and $first_color_in_list equals blue.

Though push, pop, shift, and unshift are the most common list array manipulation functions used, there are many others covered in more complete references. The following table summarizes some of the common array manipulating operators.

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
sort (@array) Sorts the elements in @array
reverse(@array) Reverses the order of the elements in @array
chop (@array) chops off the last character of every element in @array
split (/delimiter/, string) Creates an array by splitting a string
join (delimiter, @array) Creates a scalar of every element in @array joined by the delimiter.

Previous | Next | Table of Contents