|
||
|
Lesson 9
Objective
|
Array subscripts in Perl Access array element using a foreach loop. |
|
|
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" ); for loop, you could print it like this:
for($i = 0; $i < scalar @bestpix; $i++)
{
print "$bestpix[$i]\n"
}
That method contained elements from the C programming language, and while it works fine, there are other ways to do it in Perl.
The 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
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
join function joins each of the elements of a list using whatever string is specified in the first argument.
Here's how you would get the same results again, using join:
print join("\n", @bestpix), "\n";
print join(", ", @bestpix), "\n";
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.
|
||
|
|
||
