Arrays #1

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

Arrays hold lists of items, such as numbers or strings.

Arrays are indexed numerically, starting at 0 for the first element.

We assume your system already has Perl installed, and you have a terminal or shell window opened. If not please do so since it will be much better to learn about this if you can actually see it working.

You should also have a text editor (not a word processor) with which you can create and save files. Yes, you are going to WORK for this.

Create a directory for these Perl files - it doesn't matter where but perhaps on your Desktop is easiest.

In your shell window, cd to that directory.

Now in your editor, type or paste the following in a new file:

#!/usr/bin/perl
use strict;
use warnings;

Save the file as arrays1.pl - make sure it is in the directory you just created.

This is how all your Perl scripts should begin.
The first line contains the 'path' to your Perl program - if your Perl is somewhere else put that path in instead.

You're going to create your first array yourself, but arrays may be 'populated' by several other means. They can be created by reading a file into memory; or accessing a database for a set of records, or ...

So let's set up a small array to work with. Add this line (or paste it) to arrays1.pl:

my @foo = ("bravo","charlie","echo","alpha","foxtrot","delta");

Now the magick - to print the array to the terminal add these lines to arrays1.pl ...

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

'@foo' is the name of the variable we will use as our array.

The '$_' is a special Perl variable and stands for the current item when it appears in a loop, as above.

Save the file - it should be in the directory / folder you just made - ensure that it is.

To test your first example, enter:

perl arrays1.pl
in the terminal window.

Here is what you should see:

Well, maybe not the same background colour, but you should at least see the list of words.

Not very exciting (yet) but this is your first Perl script! Congratulations.