15

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?

2
  • "What does a plus sign in perl map mean?" I don't see map in your code. Commented Jan 16, 2014 at 21:49
  • @ThisSuitIsBlackNot some people call a hash a map, so maybe that is what Nosrettap meant?
    – asjo
    Commented Jan 16, 2014 at 22:02

2 Answers 2

21

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

1
  • 10
    It's worth mentioning that + 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
8

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.