"Perl for Perl Newbies" - Part 1ArraysBuilt-In Array Functions

9.4. Built-In Array Functions

push

The push function appends an element or an entire array to the end of an array variable. The syntax is push @array_to_append_to, @array_to_append or push @array, $elem1. For example, the primes program from earlier could be written as:

# Put 2 as the first prime so we won't have an empty array,
# what might confuse the interpreter
@primes = (2);

MAIN_LOOP:
for $number_to_check (3 .. 200)
{
    foreach $p (@primes)
    {
        if ($number_to_check % $p == 0)
        {
            next MAIN_LOOP;
        }
    }

    # If we reached this point it means $number_to_check is not
    # divisible by any prime number that came before it.
    push @primes, $number_to_check;
}

foreach $p (@primes)
{
    print $p, ", ";
}
print "\n";

Notice that push is equivalent to typing @array = (@array, $extra_elem), but it is recommended to use it, because it minimises error and it executes faster.

pop

pop extracts the last element from an array and returns it. Here's a short example to demonstrate it:

# This program prints the numbers from 10 down to 1.
@numbers = (1 .. 10);
while(scalar(@numbers) > 0)
{
    $i = pop(@numbers);
    print $i, "\n";
}

shift

shift extracts the first element of an array and returns it. The array will be changed to contain only the elements that were present there previously, with the 1 to scalar(@array)-1 indexes.

Here's the above example, while using shift instead of pop:

# This program prints the numbers 1 to 10.
@numbers = (1 .. 10);
while(scalar(@numbers) > 0)
{
    $i = shift(@numbers);
    print $i, "\n";
}

join

The syntax is join($separator, @array) and what it does is concatenates the elements of @array while putting $separator in between. Here's an example:

@myarray = ("One fish", "Two fish", "Red Fish", "Blue Fish");

print join("\n", @myarray), "\n";

reverse

The reverse function returns the array which contains the elements of the array passed to it as argument in reverse. Here's an example:

print "Enter some lines:\n";

$line = <>;
chomp($line);
while ($line)
{
    push @mylines, $line;
    $line = <>;
    chomp($line);
}

print "Your lines in reverse are:\n", join("\n", reverse(@mylines)), "\n";

Note that by typing scalar(reverse($scalar)) you get the string that contains the characters of $scalar in reverse. scalar(reverse(@array)) concatenates the array into one string and then reverses its characters.


Written by Shlomi Fish