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?
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}
becauseCONSTANT
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 sayCONSTANT() => 'value'
(or simply use a comma in place of the big arrow) instead ofCONSTANT => 'value'
.
+
is the unary plus operator, which simply yields the value of its operand. It's basically a no-op, used here to tweak the syntax.
Commented
Jan 16, 2014 at 22:38
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 +
.
map
in your code.