这个 Perl 布尔语法有什么问题?

发布于 2024-08-25 02:20:07 字数 566 浏览 4 评论 0原文

我需要在这些条件下使用黑客:

  • 这是数据的最后一页。
  • 这也不是第一页。
  • 不存在页面大小为偶数的数据项。

所以我尝试了这段代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰魂雪魄 2024-09-01 02:20:07

好的,运算符优先级。 and 几乎是 Perl 中所有运算符中优先级最低的,因此 Perl 以一种奇怪的顺序计算表达式。切换到 && 相反,我得到了正确的结果。布拉格。

您了解的更多

编辑:
正如 Philip Potter 在下面指出的,Perl 最佳实践(第 70 页)建议始终使用 &&,||, ! 来表示布尔条件 - 限制 和ornot 用于控制流,因为它们的优先级较低。 (它甚至说永远不要使用 andnot,仅使用 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 - 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!

茶色山野 2024-09-01 02:20:07

将 RHS 括在括号中:

my $use_hack = (
   $last_page_number == $current_page_number and
   $page_number != 1 and
   $total_items % $items_per_page != 0);

and 运算符相比,赋值 (=) 具有更高的优先级。您可以查看Perl 运算符优先级

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文