Arrays #4

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

Now that we have a small array of words (@foo), we want to do a few things with it.

  1. we want to sort it
  2. we want to see all the items

But before we do that let's include the whole NATO set of alphabet words. Open the file arrays1.pl in your trusty text editor again and add the following lines to the bottom:

@foo = ("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");

You may wonder about using the same array name (@foo) as previously, but this is a perfectly legal thing to do in Perl (and most languages). That's why they are called 'variables'.

Just copy and paste all the above lines into your Perl file - there are 3 lines.

I've already sorted this list, so you don't have to worry about that. You're welcome. Feel free to mix them up and practice sorting.

Whenever we want to do something to all the items in a list of some kind, we have to use a programming technique called a 'loop'. This does exactly what it sounds like - it loops over the list doing something with each item.

This is a very common thing in programming and very important to understand.

There are several ways we can perform a loop, but here is a simple way for now.

Add the following code to your Perl script:

foreach (@foo) {
    print "$_\n";
}

Run the script again. If you see a list of all those words (each on a separate line) then you did excellently!

Since loops are so common in programming, most languages have a mechanism to iterate over a list easily. In Perl we can use the 'foreach' function. It kind of does what it sounds like - 'for each of the following list of items' do something.

Following the 'foreach' of course is the something we want to iterate over: '@foo'. Note that we enclose it in parentheses.

Next we start telling the script what we want to do with each item in the list. This set of instructions is contained in a 'block' of code. We always start a block of code with an opening brace ' { ' and end it with the closing brace ' } '. It is extremely important to remember to close all your blocks correctly.

In this block we only have 1 instruction - to print the current item in our iteration over the array. The funny variable $_ is a special Perl variable which refers to the current item in a loop of some kind. Do not assign anything else to it on pain of death.

Throughout our script development you may wonder what \n means. Good catch. It means a 'newline' in computerese. In English it means add a 'carriage return'.

So our block of code simply instructs Perl to print each item in our array, and add a carriage return.

Again maybe interesting, but how useful? We may only want a certain range of items, or a certain number of items to work with.

Since arrays are indexed by a number, we need to be able to access our array by a series of continuous numbers, from the first element of the array to the last element of the array.

Recall from the 2nd tutorial that the index of the first element in an array is '0', and the last element in an array is referred to as $# (think 'number of elements').

We can now create a loop to print only certain items in our array. Let's use this method to print the whole list again.

print "\nThe other 9 yards:\n";
for (0 .. $#foo) {
    print "\t$_: $foo[$_]\n";
}

You should recognize the 'range operator' ( .. ) in the 'for' line. In the 'print' line we add a new character \t which means print a tab. The tab is followed by the current item in the list $_, then print the item located in the array at that index $foo[$_], finally a 'newline' after the word.

Continuing our exploration of loops, here is how we could print the items from #15 to #22:

print "\nThe middle ground:\n";
for (14 .. 21) {
    print "$_: \t$foo[$_]\n";
}

Again, remember we are out by 1 on the index.

To print the same list a different way, we will introduce another way of writing a loop. You will see this method used very frequently in many examples of code you look at. Get used to it and make sure you understand it.

print "\nThe other middle:\n";
for (my $i=14; $i<=21; $i++) {
    print "$i: \t$foo[$i]\n";
}

There are several new things going on here. First, in the 'for' loop we introduce the use of a variable to use as a counter $i.

This type of loop is known as a 'for loop', and has some common features. The 'for' line is usually followed by a set of conditions affecting the index, or counter, we are using.

We start out with the first condition by assigning $i to '14', since we want to start at element #14. Then we have a condition that $i must meet in order to continue - in this case if it is less than or equal to 21. Lastly, we have a condition that increments $i by 1 each time through the loop. That's what $i++ indicates.

We start a block of code with the opening brace ' { ' and make sure to close it later with a closing brace ' } '.

In the middle is the code we want to execute each time through the loop.

So our loop should print the items in our array from #14 to #21, then stop.

This is what our list contains:

Indices allow us to access any individual or group of items, not necessarily in order.

We could print say, #3, #6, #12, #14, #20, and #25 like this:

In order to do this we utilize something called an 'array slice'.

my @arrayslice=@foo[3,6,12,14,20,25];
print "\nIt's always a slice:\n";
foreach (@arrayslice) {
    print "$_\n";
}

Here we assign a new array (@arrayslice) to some parts of our original (@foo) array.

In our 'for loop' we again use the 'foreach' method to print each item in the list.

If you've managed to get this far, congratulations. As a reward here is a link to download the script 'arrays1.pl' in case you've been having some grief with it.

I've renamed the file to 'arrays1.txt' so as not to cause problems with your own file.

arrays1.txt

Download the file (right-click or double-click).

If all you get when you click the link is a page full of text (the actual code), do this:

  1. select the whole page: usually Ctrl-A (Windows) or Cmd-A (Mac)
  2. copy it to clipboard: Ctrl-S (Windows) or Cmd-S (Mac)
  3. paste into a NEW file in your text editor: Ctrl-V (Windows) or Cmd-V (Mac)
  4. save the file as 'arrays1-org.pl'

Once downloaded you can copy it somewhere to compare your code with.

MAKE SURE THE FILE IS NAMED 'arrays1-org.pl' BEFORE TRYING TO USE IT.