Part 3 in our continuing series on the popular scripting language, Perl. This week's article teaches you more about Perl's controlstructures - including the FOR and WHILE loops - and also introduces you toPerl's array variables.
Now that you've got the basics of array variables down, it's time for us tointroduce the "foreach" loop, one of the most useful control structures inPerl for dealing with array variables. It looks like this:
foreach some_scalar_variable (some_array_variable)
{
do this!
}
Here's an example:
#!/usr/bin/perl
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
foreach $item (@friends)
{
print("$item is a true Friend!\n");
}
And the output is:
Rachel is a true Friend!
Monica is a true Friend!
Phoebe is a true Friend!
Chandler is a true Friend!
Joey is a true Friend!
Ross is a true Friend!
The "foreach" loop works its way through the elements of an array,assigning each element to the defined scalar variable, and then executingthe statements within the curly braces. In the example above, eachsubsequent iteration of the loop sees a new value being assigned to thescalar variable $item - this continues as many times as there are elementsin the array. Once all the array elements are exhausted, the statementsfollowing the loop are executed.
An important point to note here is that the scalar variable used in the"foreach" loop is only assigned a value temporarily - once the loop hasfinished executing, the original value of the scalar variable, if any, isrestored. Take a look:
#!/usr/bin/perl
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
$item = "Superman";
foreach $item (@friends)
{
print("$item is a true Friend!\n");
}
print ("Loop done!\n");
print ('The value of $item is now ', $item);
Here's what you'll get
Rachel is a true Friend!
Monica is a true Friend!
Phoebe is a true Friend!
Chandler is a true Friend!
Joey is a true Friend!
Ross is a true Friend!
Loop done!
The value of $item is now Superman
This article copyright Melonfire 2000. All rights reserved.