next up previous contents
Next: Array Slices Up: Arrays and Lists Previous: Creating Arrays   Contents


Functions for Array and List Processing

Besides loops, perl offers a variety of functions useful for dealing with lists and arrays. To combine the elements of an array into a single scalar string, you can use the function join. The first argument to join is the string to use in between the joined pieces of the array. One very handy use of join is to print the elements of an array, one per line, by joining the array elements with the newline character (\n). When you specify a newline character in this context, make sure to surround it with double quotes, not single quotes, or a backslash and an ``n'' will be used to join the pieces of the array.

Thus, to print the numbers from 1 to 10, each on a single line, you could use the following perl statement:

     print join("\n",1..10);

Perl offers two sets of functions which are useful for creating and manipulating arrays: push and pop, and unshift and shift. The first function of each pair adds a scalar, array or list to an array, while the second function of each pair removes a element from an array, shortening the array by one element. These functions are useful in maintaining a stack and in processing command line and function arguments. The difference between the two sets of functions concerns whether values are added and/or removed from the front of the array (unshift/shift) or from the end of the array (push/pop). When you access an element of an array using shift or pop, remember that the element is removed from the array, and can not be accessed from the array later.

A more general function for manipulating arrays is splice. The first argument to splice is the array to be modified. The second argument is the subscript corresponding to the first element to be removed from the array, and the third argument is the number of elements to be removed. With no fourth argument, splice simply removes the designated elements from the array; with a fourth argument (either scalar or array), splice inserts new values in place of the ones removed. You can specify a value of 0 for the third argument if you simply want to insert new values without removing any of the existing ones. Since splice automatically expands or shrinks the array, it provides a very simple way to add or remove values anywhere you want inside an array.


next up previous contents
Next: Array Slices Up: Arrays and Lists Previous: Creating Arrays   Contents
Phil Spector 2002-10-18