Table of Contents

Basic Array Work

For example, an array is an ordered list of scalar variables. This list can be referred to as a whole, or you can refer to individual elements in the list. The program below defines a an array, called @names . It puts five values into the array.


@names=("Muriel","Gavin","Susanne","Sarah","Anna");

print "The elements of \@names are @names\n";
print "The first element is $names[0] \n";
print "The third element is $names[2] \n";
print 'There are ',scalar(@names)," elements in the array\n";

Firstly, notice how we define @names . As it is in a list context, we are using parens. Each value is comma separated, which is Perl's default list delimiter. The double quotes are not necessary, but as these are string values it makes it easier to read and change later on.

Next, notice how we print it. Simply refer to it as a whole, that is in list context.. List context means referring to more than one element of a list at a time. The code print @names; will work perfectly well too. But....

I usually learn something about Perl every time I work with it. When running a course, a student taught me this trick which he had discovered:


@names=("Muriel","Gavin","Susanne","Sarah","Anna","Paul","Trish","Simon");

print @names;
print "\n";
print "@names";

When a list is placed inside doublequotes, it is space delimited when interpolated. Useful.

If we want to do anything with the array as a list, that is doing something with more than one value, then refer to the array as @array . That's important. The @ prefix is used when you want to refer to more than one element of a list.

When you refer to more than one, but not all elements of an array that is known as a slice . Cake analogies are appropriate. Pie analogies are probably healthier but equally accurate.