when with Many Items
Sometimes you’ll want to go through many items, but given takes only one thing at a time. In this
case, you could wrap given in a
foreach loop. If you wanted to go
through @names, you could assign the
current element to $name, then use
that for given:
use 5.010;
foreach my $name ( @names ) {
given( $name ) {
...
}
}Guess what? Yep, that’s too much work. (Are you tired of all of
this extra work yet?) This time, let’s alias the current element of
@names just so given can alias it also. Perl should be
smarter than that! Don’t worry, it is.
To go through many elements, you don’t need the given. Let foreach put the
current element in $_ on its own. If
you want to use smart matching, the current element has to be in
$_.
use 5.010;
foreach ( @names ) { # don't use a named variable!
when( /fred/i ) { say 'Name has fred in it'; continue }
when( /^Fred/ ) { say 'Name starts with Fred'; continue }
when( 'Fred' ) { say 'Name is Fred'; }
default { say "I don't see a Fred" }
}If you are going to go through several names though, you probably
want to see which name you’re working on. You can put other statements
in the foreach block, such as a
say statement:
use 5.010;
foreach ( @names ) { # don't use a named variable!
say "\nProcessing $_";
when( /fred/i ) { say 'Name has fred in it'; continue }
when( /^Fred/ ) { say 'Name starts with Fred'; continue }
when( 'Fred' ) { say 'Name is Fred'; }
default { say "I don't see a Fred" }
}You can even put extra statements between the when ...