gpt4 book ai didi

perl - switch 语句和 if 语句之间的差异

转载 作者:行者123 更新时间:2023-12-04 23:09:24 25 4
gpt4 key购买 nike

这两个语句的行为是否相同,还是会产生不同的结果?

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;

最佳答案

您所谓的“固定”版本现在在代码的两个版本中做了不同的事情。检查哈希中是否存在键与检查关联值是否为真完全不同。

您可以从散列中获得三种不同的真值 - 键是否存在于散列中、关联值是否已定义以及关联值是真还是假。此代码应演示三者之间的区别:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
key1 => undef,
key2 => 0,
key3 => 1,
);

foreach (qw(key1 key2 key3 key4)) {
check_key($_);
}

sub check_key {
my $k = shift;

print "Key $k ";
if (exists $hash{$k}) {
print 'exists. ';
} else {
print "doesn't exist. ";
}

print 'Value ';

if (defined $hash{$k}) {
print 'is defined ';
} else {
print 'is not defined ';
}

print 'and is ';

if ($hash{$k}) {
print "true\n";
} else {
print "false\n";
}
}

关于perl - switch 语句和 if 语句之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4302096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com