Pages

For each loop

The for each loop is very handy when you want to do something on all the items in an array.

Here we have, again, this array:
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
, we want to print it, but this time we want to show each month name on a different line.

As often happens in Perl, this is a one liner:
for my $month (@months) { print $month, "\n"; }
I declared month as a scalar variable local to the for each loop. Any round in the loop it gets a value from the array months, till the end of it is reached.

Actually, we could rewrite the loop in a even more succint way:
for (@months) { print $_, "\n" }
No loop variable is required, we can safely use the default scalar variable $_ instead, and we can even get rid of the last semicolon in the for each body.

Another example, where there is a change in the array we are working with. The problem here is that we want to double each value in an array:

my @values = ( 10, 20, 30, 40, 50 );
print "initial values: @values\n";
for(@values) { $_ *= 2 }
print "final values: @values\n";

Again a compact solution.

Chapter 3 of Beginning Perl by Simon Cozens is about arrays and associative arrays (hashes).

No comments:

Post a Comment