Next: Variable scoping
Up: Simple for () {}
Previous: Simple for () {}
Contents
Index
As an aside, in a for() loop Perl offers you an option
of not specifying a variable to be assigned to each element
in the list, but rather use a special variable $_ instead.
A loop using this syntax is
my @arr = (1, 2, 3, 4, 5); # can also write this as @arr = (1 .. 5);
for (@arr) {
print qq{The current element is now $_\n};
}
Whether to use this feature or not is up to you - for long
loops, or nested loops, the use of $_ can be
confusing, but for short loops, it can make for shorter,
and more readable, code. One place though where this syntax
is widely used is in the map and grep functions
for constructing lists from lists. map is used as
@b = map {block_of_statements} @a;
which will construct an array @b from an array @a by
applying block_of_statements to each element of @a.
Similarly, grep is used as
@b = grep {block_of_statements} @a;
which will construct an array @b from the list of
elements in array @a which satisfy the conditions
specified by block_of_statements. For example,
if we had an array @a = (1 .. 20) (all integers between
1 and 20 - the two dots are called the range operator),
then in
@b = map { $_ ** 2} @a;
each element of @b will be the square of the
corresponding element in @a. Similarly,
@b = grep {$_ % 2 == 0} @a;
will construct @b from all those elements in @a
which are even ($a % $b divides an integer $a by
an integer $b and returns the remainder).
Next: Variable scoping
Up: Simple for () {}
Previous: Simple for () {}
Contents
Index