加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

为什么//在perl中的优先级低于相等性?

发布时间:2020-12-15 21:48:04 所属栏目:大数据 来源:网络整理
导读:为什么//的优先级低于(至少)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; 打印(对我来说)非常意外的结果. 解决方法 这是因为//属于操作符的类别,以及==. ==是
为什么//的优先级低于(至少)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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读