Reputation: 2670
I have a function that checks if data is valid (i.e. non-negative), and is supposed to warn then exit the sub. The issue I am running into is that the warning is being suppressed. Can anyone explain why the warning is being suppressed?
#!/usr/bin/perl
use strict;
use warnings;
my $a = b();
print "Function returned $a\n";
sub b
{
my $a = -1;
($a >= 0) || (warn "\$a is negative" && return 0);
print "Passed negative check\n";
return 1;
}
The output that I receiving is
Function returned 0
Upvotes: 1
Views: 90
Reputation: 386646
Precedence issue.
warn "\$a is negative" && return 0
means
warn("\$a is negative" && return 0)
You want
warn "\$a is negative" and return 0
or
warn("\$a is negative") && return 0
Better yet, apply both changes.
warn("\$a is negative") and return 0
Be wary of pitfalls when you omit parens around argument lists.
Generally, use and
and or
if the RHS expression consists of a flow-control expression such as die
, return
, next
, last
, redo
or exit
.
Actually, why are you checking what warn
returns? You actually want
warn("\$a is negative"), return 0
or
do { warn "\$a is negative"; return 0 }
So we get
$a >= 0
or warn("\$a is negative"), return 0;
or
$a >= 0
or do {
warn "\$a is negative";
return 0;
};
But I suspect most people would prefer seeing
if ($a < 0) {
warn "\$a is negative";
return 0;
}
Upvotes: 7