views:

141

answers:

2

I have hack I need to employ under these conditions:
-It's the last page of data.
-It's not the first page, either.
-There's not a page-size-even number of data items.

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.

+6  A: 

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.

codaddict
Simultaneous discovery! So the next question is 'Which is better?'
wes
Philip Potter
+12  A: 

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.

The More You Know.

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!

wes
That is correct!
Ether
Use `and`/`or` for `my $foo = blarg() or die 'blarg is broke';` Use `` Always consider precedence: `$foo = $a and blarg()` is very different than `$bar = $b `
daotoad