Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't "x = a or b" work in Perl?

Tags:

perl

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?

like image 365
jackthehipster Avatar asked Sep 01 '14 09:09

jackthehipster


1 Answers

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
like image 104
mpapec Avatar answered Oct 10 '22 21:10

mpapec