'Test two boolean values with AND operator in Perl
I want to test two boolean values in Perl. In case both are 0 do x, in case not do y. For example: $var1 = 0; false in Perl $var2 = 0; false in Perl
if($var1==0 && var2==0)
{
x //both are false
}
else
{
y //both are true
}
Solution 1:[1]
if ( $var1 && $var2 ) {
# Both are true.
}
elsif ( !$var1 && !$var2 ) {
# Both are false.
}
or
if ( !( $var1 xor $var2 ) ) {
# Both are true or both are false.
if ( $var1 ) {
# Both are true.
} else {
# Both are false.
}
}
or
if ( $var1 ) {
if ( $var2 ) {
# Both are true.
}
} else {
if ( !$var2 ) {
# Both are false.
}
}
Solution 2:[2]
So … assuming you want y only when both $var1 and $var2 are true:
if (!$var1 and !$var2) {
# do x
} elsif ($var1 and $var2) {
# do y
}
But there TIMTOWTDI. Because Perl.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Daniel Lathrop |