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

In other languages โ€‹โ€‹I would write

testvar = onecondition OR anothercondition; 

so testvar is true if any condition. But in Perl, this does not work as expected.

I want to check a condition when either the content variable is empty or it matches a certain regular expression. I have this 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 expect $ res to contain "1" or something that has the value "true" when testing with if (). But it contains an empty string.

How can I achieve this in Perl?

+5
source share
2 answers

Put parentheses around the expression,

 my $res = ($cond1 or $cond2); 

or use the higher priority operator || ,

 my $res = $cond1 || $cond2; 

since your code is interpreted by perl as (my $res = $cond1) or $cond2; or more precisely

 perl -MO=Deparse -e '$res = $cond1 or $cond2;' $cond2 unless $res = $cond1; 

If you used use warnings; , he would also warn you about $cond2 ,

 Useless use of a variable in void context 
+19
source

@jackthehipster: you did everything right, just put the brackets for $cond1 or $cond2 , as shown below:

 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";} 
+1
source

Source: https://habr.com/ru/post/1201555/


All Articles