Nosrettap
Nosrettap

Reputation: 11340

What does a plus sign mean in a hash?

I have the following piece of Perl code, but I can't understand what its doing.

use constant ANIMAL => 'rabbit'; 
if ($self->{+ANIMAL}) {
    # Do something here
}

What does the + sign before the constant ANIMAL mean?

Upvotes: 15

Views: 3368

Answers (2)

Kenosis
Kenosis

Reputation: 6204

Building upon Denis Ibaev's response, B::Deparse can show how the code is parsed with and without using the +:

perl -MO=Deparse,-p script.pl

With +:

use constant ('ANIMAL', 'rabbit');
if ($$self{+'rabbit'}) {
    ();
}
script.pl syntax OK

Without +:

use constant ('ANIMAL', 'rabbit');
if ($$self{'ANIMAL'}) {
    ();
}
script.pl syntax OK

Note that the + invokes using the constant where the bareword ANIMAL is used without the +.

Upvotes: 8

Denis Ibaev
Denis Ibaev

Reputation: 2520

From perldoc constant:

You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example, you can't say $hash{CONSTANT} because CONSTANT will be interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value'.

Upvotes: 21

Related Questions