user1895140
user1895140

Reputation: 109

What is the meaning of operator ||=

In Perl, what's the meaning of operator ||= in the following example ?

$sheet -> {MaxCol} ||= $sheet -> {MinCol};

Upvotes: 6

Views: 197

Answers (3)

Wolfgang
Wolfgang

Reputation: 1

As the other answers said: it's one of the shorthands Perl offers.

$a += $b is almost identical to $a = $a + $b.

Why almost? Well, the number of accesses to $a might cause different side effects. For example if $a is actually a tied variable. Tie-ing a variable/hash/array/filehandle gives you hooks into reading from and writing to storage (be it RAM that Perl took or a database file somewhere or simple access to sensors (temperature, humidity, ... )

See perldoc -f tie for more information.

You probably can already imagine that this can be very powerful, not unlike Unix' "everything is a file" access to all kinds of devices through a pretty unified and universal interface ...

There are other shorthands in Perl:

  • $a **= $b (as in $a is $a to the power of $b),
  • +=, -=, */, /= --- pretty much as it says on the tin,
  • %= modulo
  • $a x= $b, repeating the string in $a tor $b times
  • &=, |=, ^=, bitwise and, or, XOR
  • &.=, |.=, ^.=, same &= etc. but operands are forced to be interpreted as strings
  • <<=, >>= are for bitwise shifting
  • $a &&= $b is "if $a evaluates as true, set it to $b".
  • ||= is "if $a evaluates as false (empty string, value zero or undefined), set $a to $b. A great way to set default values if 0 or empty string cannot be valid input.
  • \\=, my favourite, is nearly the same as ||= except it will not set $a to $b even if $a is 0 or an empty string.

Upvotes: 0

Andomar
Andomar

Reputation: 238296

a ||= b is similar to a = a || b, so:

$sheet->{MaxCol} ||= $sheet->{MinCol};

is similar to:

$sheet->{MaxCol} = $sheet->{MaxCol} || $sheet->{MinCol};

Per ikegami's comment, the difference is that a ||= b; only evaluates a once, and it evaluates a before b. This matters when a is magical or isn't a scalar.

Upvotes: 7

mpapec
mpapec

Reputation: 50677

$sheet -> {MaxCol} ||= $sheet -> {MinCol};

have same effect as

if (!$sheet->{MaxCol}) { $sheet->{MaxCol} = $sheet->{MinCol}; }

or

$sheet->{MaxCol} = $sheet->{MinCol} unless $sheet->{MaxCol};

Upvotes: 5

Related Questions