Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean for an operator to bind in Perl?

For instance, in "Programming Perl", there are sentences such as this one:

These string operators bind as tightly as their corresponding arithmetic operators.

In other places, both in "PP" and in perldoc, the authors use phrasing such as "binds tightly"; for instance, when referring to =~, or "binds even more tightly" when referring to ** (exponentiation).

If this were the same as precedence, it would not be possible to say things like "even more tightly", I'm guessing. You'd say "higher/lower precedence" instead.

So what exactly does it mean for an operator to bind?

like image 705
minya Avatar asked Nov 27 '12 23:11

minya


2 Answers

This refers to operator precedence. In the statement

a = b + c * d

The multiplication has higher precedence, and therefore "binds" more tightly than addition.

Operators that bind more tightly are evaluated before less-tightly bound operators.

like image 141
Jim Garrison Avatar answered Nov 04 '22 00:11

Jim Garrison


You may have a look at the precedence list in the documentation and compare it with the texts you read. I feel pretty sure that they are talking about precedence, though.

Precedence is a form of binding, in that it "glues" arguments together with different strength. A common mistake people make, for example, is using:

open my $fh, "<", "input.txt" || die $!;

Which is a silent and deadly error, because || "binds more tightly"/has higher precedence than the comma , operator, so this expression becomes:

open my $fh, "<", ("input.txt" || die $!);

And since the string "input.txt" is always true, no matter what, since it is a constant, the die statement is never used. And the open statement can therefore fail silently, leading to hard to find errors.

(The solution is to use the lower precedence operator or instead of ||, or as mob points out, override precedence by using parentheses.)

like image 6
TLP Avatar answered Nov 04 '22 01:11

TLP