Multiple comparison of string variable in perl -


i'm trying make kind of bash-like case statement in perl using if operator.

my $var = shift @argv; print "err\n" if (!$var || ($var ne "one") || ($var ne "two")); 

the problem is, 'if' statement not work expected. example, if pass input 'one' or 'two' prints 'err', but, if swap 'ne' 'eq' script works correctly.

perl version 5.16.3 linux

read on de morgan’s laws:

not($p && $q) == (!$p || !$q) not($p || $q) == (!$p && !$q) 

if allowed values "one" or "two", write:

print "err\n"   unless defined $var      , $var eq "one" || $var eq "two"; 

if want use ne, then:

print "err\n"   if ! defined $var   or $var ne "one" && $var ne "two"; 

these 2 forms equivalent. if have more 2 allowed strings, gets easier , more efficient using hash:

my %allowed; @allowed{"one", "two"} = ();  print "err\n" unless defined $var , exists $allowed{$var}; 

the problem code was: when or-ing multiple conditions together, sufficient 1 sub-condition true whole condition true.

given undef or other false value, !$var true.
given string "one", $var ne "two" true.
given other string, $var ne "one" true.

therefore, ($var ne "one") || ($var ne "two") true.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -