这个 Perl 布尔语法有什么问题?
我需要在这些条件下使用黑客:
- 这是数据的最后一页。
- 这也不是第一页。
- 不存在页面大小为偶数的数据项。
所以我尝试了这段代码:
my $use_hack =
$last_page_number == $current_page_number and
$page_number != 1 and
$total_items % $items_per_page != 0;
我不断收到关于最后一个条件的警告 Useless use of numeric ne (!=) in void context
,并且当 $total_items % $items_per_page = 0 时评估为 true
。
say 'NOT EVEN' if $total_items % $items_per_page != 0; #works properly, though...
我尝试了各种括号组合来使其正确,但似乎没有任何效果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,运算符优先级。
and
几乎是 Perl 中所有运算符中优先级最低的,因此 Perl 以一种奇怪的顺序计算表达式。切换到&&
相反,我得到了正确的结果。布拉格。您了解的更多。
编辑:
正如 Philip Potter 在下面指出的,Perl 最佳实践(第 70 页)建议始终使用
&&,||, !
来表示布尔条件 - 限制和or
和not
用于控制流,因为它们的优先级较低。 (它甚至说永远不要使用and
和not
,仅使用or
作为后备逻辑。)谢谢大家!
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 - limitingand or
andnot
for control flow because of their low precedence. (And it even goes so far as to say to never useand
andnot
, onlyor
for fallback logic.)Thanks, everybody!
将 RHS 括在括号中:
与
and
运算符相比,赋值 (=
) 具有更高的优先级。您可以查看Perl 运算符优先级。Enclose the RHS in parenthesis:
Assignment (
=
) is having higher precedence when compared toand
operator. You can take a look at the Perl Operator Precedence.