perl – switch-和if-语句之间的差异
这两个陈述是否表现相同,还是会产生不同的结果?
if ( ... ) {...} elsif( ... ) {... } elsif( ... ) { ... } else { ... } . given ( ... ) { when ( ... ) { ... } when ( ... ) { ... } default { ... } } 我发现了问题 – 修改后的第九个“当它”现在有效. ... no warnings qw(numeric); my $c = &getch(); given ( $c ) { when ( $c == $KEY_LEFT and 1 > 0 ) { say 1; say $c } when ( $c == $KEY_RIGHT ) { say 2; say $c } when ( $c eq "cH" or $c eq "c?" ) { say 3; say $c } when ( $c eq "cC" ) { say 4; say $c } when ( $c eq "cX" or $c eq "cD" ) { say 5; say $c } when ( $c eq "cA" ) { say 6; say $c } when ( $c eq "cE" ) { say 7; say $c } when ( $c eq "cL" ) { say 8; say $c } when ( not( not $SpecialKey{$c} ) ) { say 9; say $c } when ( ord( $c ) >= 32 ) { say 10; say $c } default { say 11; say $c } } if ( $c == $KEY_LEFT and 1 > 0 ) { say 1; say $c } elsif ( $c == $KEY_RIGHT ) { say 2; say $c } elsif ( $c eq "cH" or $c eq "c?" ) { say 3; say $c } elsif ( $c eq "cC" ) { say 4; say $c } elsif ( $c eq "cX" or $c eq "cD" ) { say 5; say $c } elsif ( $c eq "cA" ) { say 6; say $c } elsif ( $c eq "cE" ) { say 7; say $c } elsif ( $c eq "cL" ) { say 8; say $c } elsif ( $SpecialKey{$c} ) { say 9; say $c } elsif ( ord( $c ) >= 32 ) { say 10; say $c } else { say 11; say $c } close TTYIN; 解决方法
无论你使用给定/何时做什么,都可以使用if / elsif / else.我们的想法是,当/ /被认为更容易阅读时,默认情况下可以自动使用智能匹配,而您必须使用if / else语句指定智能匹配.
我没有解析你的代码,以确保它们是完全等价的,但看起来你或多或少有关于if / elsif / else和given / when的正确想法. 我从未真正理解对所谓的switch语句的渴望.这是Perl编码员总是抱怨的东西 – 在Perl中缺少switch语句.也许这是大多数Perl开发人员深情记忆的C事物.但我从来没有发现if / elsif / else语句那么糟糕. 让我感到困惑的是,当他们最终实现switch语句时,他们并没有将其称为切换.为什么不呢? 为什么说而不是printnl? 并且,为什么最后和下一个而不是休息和继续.为什么不简单地使用其他语言已经使用的标准名称? 但足够的这种Seinfeld风格抱怨…… 正如davorg所说,不存在的哈希密钥,存在但未定义的哈希密钥,以及已定义的哈希密钥,但被评估为假的哈希密钥之间存在很大差异: 例如: use strict; use warnings; no warnings qw(uninitialized); my %hash; $hash{FOO} = "bar"; if (not exists($hash{BAR})) { print "$hash{FOO} doesn't existn"; } if (not defined($hash{BAR})) { print "$hash{BAR} is undefinedn"; } if (not $hash{BAR}) { print "$hash{BAR} evaluates to falsen"; } if ($hash{BAR} eq undef) { print "$hash{BAR} is equal to 'undef'n"; } 您可以看到$hash {BAR}甚至不作为%哈希哈希中的键存在,但它也是未定义的,并且它的计算结果为false.并且,您还可以看到它也评估为undef(注意我不必设置警告qw(未初始化);以防止它抱怨$hash {BAR}在我的上一个if语句中未初始化). 但是,如果我这样做: $hash{FOO} = bar; $hash{BAR} = undef; 第一个if语句不再评估为true,因为键BAR现在确实存在于哈希中,但该值仍未定义且仍然计算为false. 而且,如果我这样做: $hash{FOO} = bar; $hash{BAR} = 0; $hash {BAR}现在作为%hash中的键存在,并且不再是未定义的,但它仍然计算为false. 我只想简单地说: if (not $hash{BAR}) { 因为它短而甜,可能做我想要的.但是,我必须了解哈希中键的存在,评估为假,而不是被定义为三个单独的东西之间的区别.如果您有一个可以返回NULL字符串或零值的子例程,这很重要: if (not foo($bar)) { die qq(Error of some sortn); } sub foo { $bar = <FOO> or return; return chomp($bar); } 如果我的文件中有一个空行,它将返回一个NULL字符串,但子程序仍将返回一个定义的值.以上可能不会做我想要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |