[英]Multiple comparison of string variable in perl
我正在嘗試使用if運算符在perl中創建某種類似bash的case語句。
my $var = shift @ARGV;
print "err\n" if (!$var || ($var ne "one") || ($var ne "two"));
問題是,'if'語句不能按預期工作。 例如,如果我輸入'one'或'two'作為輸入,則打印'err',但是,如果我將'ne'與'eq'交換,則腳本正常工作。
perl版本5.16.3 linux
閱讀De Morgan的法律 :
not($p && $q) == (!$p || !$q)
not($p || $q) == (!$p && !$q)
如果唯一允許的值是"one"
或"two"
,那么你可以寫:
print "err\n"
unless defined $var
and $var eq "one" || $var eq "two";
如果你想使用ne
,那么:
print "err\n"
if ! defined $var
or $var ne "one" && $var ne "two";
這兩種形式是等價的。 如果您有兩個以上的允許字符串,則使用哈希可以更輕松,更高效:
my %allowed;
@allowed{"one", "two"} = ();
print "err\n" unless defined $var and exists $allowed{$var};
您的代碼存在的問題是:當將多個條件放在一起時,任何一個子條件都為真,整個條件都為真就足夠了。
給定undef
或其他錯誤值, !$var
為true。
給定字符串"one"
, $var ne "two"
為真。
給定任何其他字符串, $var ne "one"
為真。
因此, ($var ne "one") || ($var ne "two")
($var ne "one") || ($var ne "two")
總是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.