Arrays #2

#0 | #1 | #2 | #3 | #4 | #5 | #6 | #7

Continuing on with our original array (@foo), let's do something useful.

Perhaps you've recognized the words in the first array - they are the first 6 words in the NATO alphabet used in voice or radio communication.

Here are all the words in the NATO alphabet (in case you want to use them):

alpha, bravo, charlie, delta, echo, foxtrot, golf, hotel, india, juliet, kilo, lima, mike, november, oscar, papa, quebec, romeo, sierra, tango, uniform, victor, whiskey, xray, yankee, zulu

But right now we are only working with the first six. Our first script printed the array exactly as we defined it - the words were not in order. To get them into a sorted list is pretty easy. We use the 'sort' function (DUH).

In your text editor, add the following lines to arrays1.pl:

my @sortedfoo = sort @foo;
print "\nSorted ...\n";
foreach (@sortedfoo) {
    print "$_\n";
}

Here we are creating a new array (@sortedfoo) by 'sorting' the original array (@foo). Then printing each element in the array.

Run the file as before (perl arrays1.pl) - you should now see this:

Well, that was pretty painless. Can we get them in reverse order? Certainly. Add the following lines to your script:

print "\nNow in reverse order:\n";
my @revsortedfoo = reverse @sortedfoo;
foreach (@revsortedfoo) {
    print "$_\n";
}

Run the script again to see if you did it right.

Looking good! They say 'Perl makes easy things easy, and hard things possible.'

Let's try it with numbers.

Create a new array and fill it with some numbers. Add the following to arrays1.pl:

my @nums=(32,1,4,8,16,2,11);
print "\nSome numbers ...\n";
foreach (@nums) {
    print "$_\n";
}

What we get from that code:

Expected result. So let's sort them. Add these lines now:

print "\nNumbers sorted incorrectly:\n";
my @sortednums = sort @nums;
foreach (@sortednums) {
    print "$_\n";
}

Hmmm. That doesn't look like we expected. Although they are sorted (sort of).

The Perl 'sort' function works in an ASCIIbetical way - sorting elements by their alphabetical value. Numbers are treated as strings unless we add some magick.

To sort numbers correctly (numerically) we must do something different.

Add these lines to the existing file ...

@sortednums = sort { $a <=> $b } @nums; # note the order of $a and $b
print "\nIn numeric order ...\n";
foreach (@sortednums) {
    print "$_\n";
}

Run the script again ...

Now we should see the right stuff:

The magical symbol '<=>' is needed to sort numbers. The '$a' and '$b' are special Perl variables used in sorting routines and must be used when sorting like this. Sorting is done by comparing 2 items - '$a' and '$b'. In the current arrangement the sort will be in ascending order. If you reverse them, the sort will be in descending order. Try it.

There is another way to sort strings using the 'comparison function': 'cmp'. If you have an array of strings (like @foo) and wanted to sort it alphabetically, you could do it the same way as this, only swap out the '<=>' and replace it with 'cmp'.

The order of '$a' and '$b' also switches the order of sorting strings.

Important point: do not use '$a' or '$b' anywhere else in your scripts except in this manner.

Add these lines to arrays1.pl:

print "Numbers in reverse order ...\n";
@sortednums = sort { $b <=> $a } @nums; # note the order of $b and $a
foreach (@sortednums) {
    print "$_\n";
}

Important point: do not mix up '<=>' and 'cmp' in your sorts.

'<=>' (aka the spaceship operator) is for numbers only

'cmp' is for strings only

More congratulations! You've learned how to create an array and sort it - up and down.

Adding & Deleting Elements

Two keywords push, pop are used to add or delete elements from the end of an array.

To add a new word to our @foo array, we 'push' it onto the array:

push @foo,'golf';
foreach (@foo) {
    print "$_\n";
}

And if you don't happen to like 'golf', you can delete it. But just in case you might want to try it again, you can save it first:

my $golfSaved = pop @foo;
pop @foo;
foreach (@foo) {
    print "$_\n";
}
print "$golfSaved just in case\n";

Adding or deleting elements at the beginning of an array is done with unshift and shift.

Your friend says he really likes golf, so wants it added to the beginning:

unshift @foo, $golfSave;

But it's your list and you don't like golf, so out it goes:

shift @golf;

Next we get more on manipulating arrays.