Chinaunix首页 | 论坛 | 博客
  • 博客访问: 858888
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-17 11:19:20

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.
  1. use 5.010;
  2. given( $ARGV[0] ) {
  3.     when( /fred/i ) { say 'Name has fred in it' }
  4.     when( /^Fred/ ) { say 'Name starts with Fred' }
  5.     when( 'Fred' ) { say 'Name is Fred' }
  6.     default { say "I don't see a Fred" }
  7.     }
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.

  1. use 5.010;
  2. given( $ARGV[0] ) {
  3.     when( $_ ~~ /fred/i ) { say 'Name has fred in it'; continue }
  4.     when( $_ ~~ /^Fred/ ) { say 'Name starts with Fred'; continue }
  5.     when( $_ ~~ 'Fred' ) { say 'Name is Fred'; break } # OK and the break can be omitted.
  6.     when( 1 == 1 ) { say "I don't see a Fred" }
  7.     }
5. the continue can instead of break.
  1. use 5.010;
  2. foreach ( @names ) { # don't use a named variable!
  3.     say "\nProcessing $_";
  4.     when( /fred/i ) { say 'Name has fred in it'; continue }
  5.     when( /^Fred/ ) { say 'Name starts with Fred'; continue }
  6.     when( 'Fred' ) { say 'Name is Fred'; }
  7.     default { say "I don't see a Fred
when with many items, we can use foreach to go through the array.

阅读(372) | 评论(0) | 转发(0) |
0

上一篇:smart match operator ~~

下一篇:system, exec, fork

给主人留下些什么吧!~~