next up previous
Next: Associative Arrays Up: Basic Perl Programming Previous: Arrays

Some Useful Array Functions

push() and pop()

One common use of an array is as a stack.

push() and pop() add or remove an item from the right hand side of an array.

push(@mystack,$newvalue); 
# add new value to stack

$off_value = pop(@mystack); 
# take last element off array

shift() and unshift()

Like push() and pop() except put values on and take values off the left side of an array.

reverse()

As one would expect this will reverse the ordering of list. For example:

@a = (1,2,3);

@b = reverse(@a);

results in b containing (3,2,1).

sort()

This is a useful function that sorts an array. NOTE: Sorting is done on the string values of each number (alphabetical)

Thus:

@x = sort("small","medium","large");

# gets @x = ("large","medium","small");

@y = sort(1,,32,16,4,2);

# gets @x = (1,16,2,32,4);

chop()

Just as on a scalar string it removes the last character of every element from an array, for example:

@x = ("small","medium","large");

chop(@x);

# gets @x =  ("smal","mediu","larg")



Dave Marshall
9/28/2001