Understanding arrays must also include how to access various elements of it.
Recall from #1 how arrays are indexed starting at 0 (zero) for the 1st element. This implies that the 2nd element would be referenced by the index 1. You would be right. Here's how it works.
Our NATO array (@foo) contains 6 elements in the form of 6 words. To access a particular element in the array we use this structure:
Note that we are now using '$' to refer to the array instead of '@' in this case. The '$' indicates we are dealing with a scalar quantity - a single item (string or number). When we want just 1 item from an array we specify it this way. This is important to remember.
In our case to refer to the 1st element, we refer to
$foo. The 2nd would be:
$foo, and so on.
This makes an array very easy to 'walk through', or access all items.
To try this out in our arrays1.pl Perl script, add the following lines to it:
print "\nThe 3rd element\n"; print "$foo\n";
We can also put that all on 1 line as follows:
print "\nThe 3rd element in the array: $foo\n";
Here is what you should see:
We can refer or access any number of discrete elements in our array. To see the 1st, 3rd, and 5th elements:
print "\nSome odd elements:\n"; print "$foo,$foo,$foo\n";
Remember that arrays are indexed starting at 0, so that is actually the index of the first element.
This may all be very interesting, but what if you want to see all the items in the array? For that we need to learn about 'loops' in the next tutorial.