February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Perl has more than one topicalizer; in addition to given, you can also use a foreach loop as a topicalizer. For
example, here’s one way to count how many times a particular string
occurs in an array:
use v5.10.1;
my $count = 0;
for (@array) {
when ("FNORD") { ++$count }
}
print "\@array contains $count copies of 'FNORD'\n";Or in a more recent version:
use v5.14;
my $count = 0;
for (@array) {
++$count when "FNORD";
}
print "\@array contains $count copies of 'FNORD'\n";At the end of all when
blocks inside a foreach loop,
there is an implicit break,
which, since you’re in a loop, is equivalent to a next. You can override that with an
explicit last if you’re only
interested in the first match.
A when only works if the
topic is in $_, so you can’t
specify a loop variable, or if you do, it must be $_:
for my $_ (@answers) {
say "Life, the Universe, and Everything!" when 42;
}Read now
Unlock full access