minya
minya

Reputation: 325

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?

Upvotes: 6

Views: 682

Answers (2)

TLP
TLP

Reputation: 67900

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.)

Upvotes: 6

Jim Garrison
Jim Garrison

Reputation: 86774

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.

Upvotes: 8

Related Questions