The given-when control structure allows you to run a block of code when the argument
to given satisfies a condition. It’s Perl’s equivalent to C’s switch statement, but as with
most things Perly, it’s a bit more fancy, so it gets a fancier name.
- use 5.010;
-
given( $ARGV[0] ) {
-
when( /fred/i ) { say 'Name has fred in it' }
-
when( /^Fred/ ) { say 'Name starts with Fred' }
-
when( 'Fred' ) { say 'Name is Fred' }
-
default { say "I don't see a Fred" }
-
}
1.the given alias its arguement to $_.
2.If $_ does not satisfy any of the when conditions, Perl executes the default block.there is a
break at the end of every when block.
3. if the first when statement is satisfied, it will break. otherwise it will do the next.
4. in this case, it can be written with if-elsif-else statement.
- use 5.010;
-
given( $ARGV[0] ) {
-
when( $_ ~~ /fred/i ) { say 'Name has fred in it'; continue }
-
when( $_ ~~ /^Fred/ ) { say 'Name starts with Fred'; continue }
-
when( $_ ~~ 'Fred' ) { say 'Name is Fred'; break } # OK and the break can be omitted.
-
when( 1 == 1 ) { say "I don't see a Fred" }
-
}
5. the continue can instead of break.
- 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
when with many items, we can use foreach to go through the array.
阅读(372) | 评论(0) | 转发(0) |