Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does // have lower precedence than equality in perl?

Tags:

perl

Why does // have lower precedence than == in (at least) perl 5.010?

For example, this

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

prints (for me) very unexpected result.

like image 442
Karel Bílek Avatar asked Dec 12 '11 02:12

Karel Bílek


1 Answers

It's because of the category of operators which // falls under, aswell as ==.

== is an "equality operator" though // falls under the category of "C-style logical operators".

As an example; && is in the same "category" as //, with that said both of the statements below are equivalent when it comes to operator precedence. That might make it easier to understand?

  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

like image 134
Filip Roséen - refp Avatar answered Oct 23 '22 21:10

Filip Roséen - refp