Perl Variables  «Prev  Next»
Lesson 9Array subscripts in Perl
ObjectiveAccess array element using a foreach loop.

Perl Array Subscripts

You can use any numeric value for an array subscript. For example, consider this array:

# AMPAS Best Picture 1980-97
@bestpix = ( 
"Ordinary People",
"Chariots of Fire", "Gandhi",
"Terms of Endearment", "Amadeus",
"Out of Africa", "Platoon",
"The Last Emperor", "Rain Man",
"Driving Miss Daisy",
"Dances with Wolves",
"The Silence of the Lambs", "Unforgiven",
"Schindler's List", "Forrest Gump",
"Braveheart", "The English Patient",
"Titanic" ); 

C-style for loop
Using a C-style for loop, you could print it like this:
for($i = 0; $i < scalar @bestpix; $i++) { 
 print "$bestpix[$i]\n" 

Perl Scalar Operator
That method contained elements from the C programming language, and while it works fine, there are other ways to do it in Perl.

Perl foreach Loop

For example, you could use the Perl foreach loop:
foreach $pic (@bestpix){
  print "$pic\n" 

The results are exactly the same, yet it's a bit easier to read.
The for and foreach constructs are explained in detail later in this course.
If you are confused by the difference between a
  1. for and a
  2. foreach loop,
keep in mind that a foreach loop increments through a defined list of values.

A for loop has no list.
The values of a for loop are defined by a beginning value, a control condition, and an increment operator.
Here is the for loop example again:
for($i = 0; $i < scalar @bestpix; $i++) 

The for loop begins with a value of $i=0, has a controlling condition of $i < scalar (when this condition is no longer true, the loop will be exited), and an increment value of $i++ or increment it one number per loop.
Perl join function
The join function joins each of the elements of a list using whatever string is specified in the first argument. Here is how you would get the same results again, using join:
print join("\n", @bestpix), "\n";

For another example, this version prints a comma-delimited list (much harder to do with the other methods):
print join(", ", @bestpix), "\n";

Access Perl Array - Exercise
These are the major methods of accessing a list or array.
Click the Exercise link below to write a program that accesses an array.
Access Perl Array - Exercise
Then, in the next lesson, we will learn about the push and pop operators, and how they work on arrays.