In other languages I would write
testvar = onecondition OR anothercondition;
to have testvar be true if either condition is. But in Perl this does not work as expected.
I want to check a condition where either a content-variable is empty, or it matches a specific regex. I have this sample program:
my $contents = "abcdefg\n";
my $criticalRegEx1 = qr/bcd/;
my $cond1 = ($contents eq "");
my $cond2 = ($contents =~ $criticalRegEx1);
my $res = $cond1 or $cond2;
if($res) {print "One or the other is true.\n";}
I would have expected $res to contain "1" or something that evals to true when tested with if(). But it contains the empty string.
How can I achieve this in Perl?
Put parentheses around expression,
my $res = ($cond1 or $cond2);
or use higher precedence ||
operator,
my $res = $cond1 || $cond2;
as your code is interpreted by Perl as (my $res = $cond1) or $cond2;
, or more accurately,
perl -MO=Deparse -e '$res = $cond1 or $cond2;'
$cond2 unless $res = $cond1;
If you were using use warnings;
it would also warn you regarding $cond2
,
Useless use of a variable in void context
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With