- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

4.11.3 Switching in a loop

Instead of using given(), you can use a foreach() loop. For example, here's one way to count how many times a particular string occurs in an array:

my $count = 0;
for (@array) {
    when ("foo") { ++$count }
print "\@array contains $count copies of 'foo'\n";

At the end of all when blocks, there is an implicit next. You can override that with an explicit last if you're only interested in the first match.

This doesn't work if you explicitly specify a loop variable, as in for $item (@array). You have to use the default variable $_. (You can use for my $_ (@array).)

ISBN 9781906966027Perl Language Reference ManualSee the print edition