Void context warning only with low priority short circuit operators

I came across a situation where and and && behave differently with respect to warnings.

Here is the original script with and .

 #!/usr/bin/env perl use strict; use warnings 'FATAL' => qw[all]; my $var1; my $var2; my $defined = (defined $var1) and (defined $var2); print ($defined ? "defined\n" : "undefined\n"); 

because the first condition is false, the second expression in and is never evaluated.

 % perl defined.pl Useless use of defined operator in void context at defined.pl line 8. Exit 255 

However, if I change the operation to a higher priority, but is otherwise identical to && , I do not receive a void warning.

 #!/usr/bin/env perl use strict; use warnings 'FATAL' => qw[all]; my $var1; my $var2; my $defined = (defined $var1) && (defined $var2); print ($defined ? "defined\n" : "undefined\n"); 

The program produces the expected result, "undefined\n" .

 % perl defined.pl undefined 

perldoc perlop suggests that and and && should be the same in all respects except for priority, but not explicitly specify it.

Alternatively, && and || when used for control flow, Perl provides operators and / or (see below). Short circuit identical. However, the priority of "and" and "or" is much lower, so that you can safely use them after the list operator without the need for parentheses:

+7
perl
source share
1 answer

The assignment operator has a higher priority than and , therefore

 my $defined = (defined $foo) and (defined $bar); 

equivalently

 (my $defined = (defined $foo)) && (defined $bar); 

You can see this with B :: Deparse :

 $ perl -MO=Deparse -e'my $defined = (defined $foo) && (defined $bar)' my $defined = defined $foo && defined $bar; -e syntax OK $ perl -MO=Deparse -e'my $defined = (defined $foo) and (defined $bar)' defined $bar if my $defined = defined $foo; -e syntax OK 
+12
source share

All Articles