I'm trying make some kind of bash-like case statement in perl by using only if operator.
my $var = shift @ARGV;
print "err\n" if (!$var || ($var ne "one") || ($var ne "two"));
The problem is, that 'if' statement does not work as expected. For example, if I pass as input 'one' or 'two' it prints 'err', but, if I swap 'ne' with 'eq' script works correctly.
perl version 5.16.3 linux
Read up on De Morgan's laws :
not($p && $q) == (!$p || !$q)
not($p || $q) == (!$p && !$q)
If the only allowed values are "one"
or "two"
, then you could write:
print "err\n"
unless defined $var
and $var eq "one" || $var eq "two";
If you want to use ne
, then:
print "err\n"
if ! defined $var
or $var ne "one" && $var ne "two";
These two forms are equivalent. If you have more than two allowed strings, it gets much easier and more efficient by using a hash:
my %allowed;
@allowed{"one", "two"} = ();
print "err\n" unless defined $var and exists $allowed{$var};
The problem with your code was: When or-ing multiple conditions together, it is sufficient for any one sub-condition to be true for the whole condition to be true.
Given an undef
or other false value, !$var
is true.
Given the string "one"
, the $var ne "two"
is true.
Given any other string, the $var ne "one"
is true.
Therefore, ($var ne "one") || ($var ne "two")
($var ne "one") || ($var ne "two")
is always true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.