Kang CiFong
Kang CiFong

Reputation: 77

Notation in Perl - what does the ||= operator do?

I happen to meet a perl code with the following syntax.

sub new{
my ($class, $value)=@_;
$lobby ||= bless{
e=>undef;},$class
}

what does the syntax ||= mean?

I failed to google it as a key word, and I could not find similar syntax in the perldoc.

Upvotes: 3

Views: 646

Answers (5)

memowe
memowe

Reputation: 2668

Just to complete this, in non-ancient versions of perl (since 5.10) you can use the defined-or operator // instead of the truth-or ||, which has better semantics when using it to set a default value:

$foo ||= 42;    # $foo = $foo || 42;

for example sets this variable's value to 42 iff $foo is false in a perlish sense. The problem is, that this operator can't distinguish defined-but-false values from undefined values because both are false.

$foo //= 42;    # $foo = $foo // 42;

This line sets $foos value iff it was undefined before, which is what we want often. It short-cirquits too, exactly like ||.

Upvotes: 3

ikegami
ikegami

Reputation: 386706

EXPR1 ||= EXPR2;

is the same as

EXPR1 = EXPR1 || EXPR2;

except EXPR1 is only evaluated once. It's a convenient way of setting a default. For example:

sub foo {
   my %args = @_;
   $args{host} ||= "localhost";  # Provide a default host name if none provided.
   ...
}

In your case, you appear to have a singleton constructor. The first time new it's called, it'll create a new object. On subsequent calls, it'll return the previously created object.

Upvotes: 7

Tokuhiro Matsuno
Tokuhiro Matsuno

Reputation: 80

$x ||= $y;

is same as

$x = $x || $y;

Upvotes: 2

user507077
user507077

Reputation:

You'll find the meaning of operators in perlop.

Now what it does: $lhs ||= $rhs is equivalent to $lhs = $lhs || $rhs. This means that $rhs is assigned to $lhs if $lhs is false in the Perlish sense. This can be if $lhs is undef, if it is an empty string, a number that is 0.

Upvotes: 9

codaddict
codaddict

Reputation: 455470

x ||= y is the short for x = x || y

See the perlop documentation.

Upvotes: 3

Related Questions