Hi, all given when支持类型匹配, 那说明given when 更趋向于函数式语言的模式匹配? 如果是这样,设计的跟switch case 不一样就是应该的了, 呵呵
2011/7/16 cnhack TNT <[email protected]> > switch ... case {} 这个语法用 if/else 很容易模拟, 所以可能 perl 不想加它们进来?另外 switch ... > case 从自然语言角度来说很别扭, 而 given ... when 就和 if ... else 一样, 非常自然, larry wall > 是语言学家, 你懂的.(个人猜测) > perl 5.8 开始, 有 Switch 模块可以实现 switch ... case, 但从 perl 5.10 开始, 就可以用更高级的 > given ... when 了. > given ... when 虽然和 C 里面的 switch ... case 很像, 但是它们并不是完全一样的 > given ... when 有如下的不同: > > 1. 匹配的时候使用 smart matching, 会根据数据类型自动调整匹配行为, > 比如说你想看给定的值是不是存在于某个数组里面,那么只要这样就行了: > given($item) { > when(@array) { say "found it!"; } > ... > } > > 不需要你针对不同数据类型做不同操作. > > 2. given ... when 的每个 when 语句块默认是 break 的, 而且其 fall through 策略是不同的, 比如你在 > when 语句最后指定了 continue, 它后面的其他 when 的判断语句还是会运行的, 而 switch ... case 不管下面的 case > 判断条件是什么, 之而后的语句一律都执行了(除非主动跳出) > > 3. given ... when 不一定需要成对出现, when 也可以用于 for 循环中(只在循环变量为默认的 $_ 时有效), 此时每个 > when 语句块的结尾默认会 next, 你可以用 continue 让when 后的语句继续执行或者 last 跳出循环 > > 4. given ... when 语句是合法的表达式, 表达式是可以求值的, 因此 given ... when 是有返回值的, 可参看: > http://perldoc.perl.org/perlsyn.html#Return-value > > > > 2011/7/16 HY@CN <[email protected]> > > 同求答案 >> >> 在 2011年7月16日 下午9:43,Beckheng Lam <[email protected]>写道: >> >> 以上是其一,另一个是为何Perl在这么多年以后,**才决定加入这个风格的语句呢? >>> >>> -- >>> 我的博客 -- http://blog.yixinit.com/ >>> 诸法从缘起,如来说是因。 >>> 彼法因缘尽,是大沙门说。 >>> >>> -- >>> 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。 >>> 要向此网上论坛发帖,请发送电子邮件至 [email protected]。 >>> 要取消订阅此网上论坛,请发送电子邮件至 >>> perlchina+unsubscribe@**googlegroups.com<perlchina%[email protected]> >>> 。 >>> 若有更多问题,请通过 >>> http://groups.google.com/**group/perlchina?hl=zh-CN<http://groups.google.com/group/perlchina?hl=zh-CN>访问此网上论坛。 >>> >>> >> >> >> -- >> HY_CN >> >> >> -- >> 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。 >> 要向此网上论坛发帖,请发送电子邮件至 [email protected]。 >> 要取消订阅此网上论坛,请发送电子邮件至 [email protected]。 >> 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。 >> > > -- > 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。 > 要向此网上论坛发帖,请发送电子邮件至 [email protected]。 > 要取消订阅此网上论坛,请发送电子邮件至 [email protected]。 > 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。 > -- 您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。 要向此网上论坛发帖,请发送电子邮件至 [email protected]。 要取消订阅此网上论坛,请发送电子邮件至 [email protected]。 若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。
