Reputation: 8175
I have hack I need to employ under these conditions:
So I tried this code:
my $use_hack =
$last_page_number == $current_page_number and
$page_number != 1 and
$total_items % $items_per_page != 0;
And I keep getting this warning Useless use of numeric ne (!=) in void context
about the last condition and it's evaluating true when $total_items % $items_per_page = 0
.
say 'NOT EVEN' if $total_items % $items_per_page != 0; #works properly, though...
I've tried various combinations of parentheses to get it right, but nothing seems to work.
Upvotes: 3
Views: 458
Reputation: 8175
Okay, operator precedence. and
has almost the lowest precedence of any operator in Perl, so Perl was evaluating the expression in a weird order. Switching to &&
instead got me correct results. Blarg.
EDIT:
As Philip Potter pointed out below, Perl Best Practices (p.70) recommends always using &&,||, !
for boolean conditions - limiting and or
and not
for control flow because of their low precedence. (And it even goes so far as to say to never use and
and not
, only or
for fallback logic.)
Thanks, everybody!
Upvotes: 14
Reputation: 454960
Enclose the RHS in parenthesis:
my $use_hack = (
$last_page_number == $current_page_number and
$page_number != 1 and
$total_items % $items_per_page != 0);
Assignment (=
) is having higher precedence when compared to and
operator. You can take a look at the Perl Operator Precedence.
Upvotes: 7