use5.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"} }
use5.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"} }
--如果$_不能满足任何when条件,perl就会执行default语句块。下面为运行结果: $ perl5.10.0 switch.pl Fred Name has fred in it $ perl5.10.0 switch.pl Frederick Name has fred in it $ perl5.10.0 switch.pl Barney I don't see a Fred $ perl5.10.0 switch.pl Alfred Name has fred in it
use5.010; given($ARGV[0]){ when($_~~/fred/i){ say 'Name has fred in it'; break } when($_~~/^Fred/){ say 'Name starts with Fred'; break } when($_~~'Fred'){ say 'Name is Fred'; break } default { say "I don't see a Fred"; break } }
use5.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';continue}# 注意! default { say "I don't see a Fred"} }
--实际上这样写是有问题的,这里的default总是会运行 $ perl5.10.0 switch.pl Alfred Name has fred in it I don't see a Fred
use5.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';continue}# 注意! when(1==1){ say "I don't see a Fred"}# 相当于default语句块 }
要解决这个问题,只要拿掉最后一个when的continue就可以了,改写成如下形式:
1 2 3 4 5 6 7
use5.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 }# 现在就对了! when(1==1){ say "I don't see a Fred"}# 这里的when(1==1)可改写成default }
use5.010; foreach(@names){# 不要使用命名变量! 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"} }
use5.010; foreach(@names){# 不要使用命名变量! 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';} say "Moving on to default..."; default { say "I don't see a Fred"} }