perl - 为什么//在perl中优先级比平等低?

标签 perl

为什么(至少)在perl 5.010中,//的优先级低于==

例如这个

use 5.010;
my $may_be_undefined = 1;
my $is_equal_to_two = ($may_be_undefined//0 == 2);
say $is_equal_to_two;

(对我来说)打印出非常意外的结果。

最佳答案

这是因为//以及==属于运算符的类别。
==是“相等运算符”,尽管//属于“C样式逻辑运算符”类别。

举个例子; &&//处于同一“类别”中,当涉及到运算符优先级时,以下两个语句是等效的。这样可能更容易理解?

  print "hello world" if $may_be_undefined && 0 == 2;
  print "hello world" if $may_be_undefined // 0 == 2;

Documentation of C-style Logical Defined-Or ( // )

Although it has no direct equivalent in C, Perl's // operator is related to its C-style or. In fact, it's exactly the same as ||, except that it tests the left hand side's definedness instead of its truth.

Thus, $a // $b is similar to defined($a) || $b (except that it returns the value of $a rather than the value of defined($a)) and yields the same result as defined($a) ? $a : $b (except that the ternary-operator form can be used as a lvalue, while $a // $b cannot).

This is very useful for providing default values for variables. If you actually want to test if at least one of $a and $b is defined, use defined($a // $b) .

The ||, // and && operators return the last value evaluated (unlike C's || and &&, which return 0 or 1).



Documentation of Operator Precedence and Associativity

关于perl - 为什么//在perl中优先级比平等低?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8469273/

相关文章:

mysql - 在 MySQL 中使用 Perl 创建带有变量的表时遇到问题

用于配置 grep 输出的 Perl 脚本

perl - 如果用户输入了空字符串,如何提示输入和退出?

perl - Perl Web 框架之间是否有任何性能比较?

regex - 用大写 perl 更改一行上的第一个字符

regex - 提取特殊字符串第一次出现之前的单词

xml - 空白子节点对 XML 解析器有用吗?

linux - 如何使用 sed 在字符串匹配后附加带有美元符号的变量?

xml - 按原样使用 XML::LibXML appendTextNode() 追加 CDATA

Perl - 将数组传递给子程序