O'Reilly logo

Programming Perl, 3rd Edition by Jon Orwant, Tom Christiansen, Larry Wall

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Braces, Brackets, and Quoting

In the previous section, we pointed out that ${identifier} is not treated as a symbolic reference. You might wonder how this interacts with reserved words, and the short answer is that it doesn't. Despite the fact that push is a reserved word, these two statements print "pop on over":

$push = "pop on ";
print "${push}over";

The reason is that, historically, this use of braces is how Unix shells have isolated a variable name from subsequent alphanumeric text that would otherwise be interpreted as part of the name. It's how many people expect variable interpolation to work, so we made it work the same way in Perl. But with Perl, the notion extends further and applies to any braces used in generating references, whether or not they're inside quotes. This means that:

print ${push} . 'over';

or even (since spaces never matter):

print ${ push } . 'over';

both print "pop on over", even though the braces are outside of double quotes. The same rule applies to any identifier used for subscripting a hash. So, instead of writing:

$hash{ "aaa" }{ "bbb" }{ "ccc" }

you can just write:

$hash{ aaa }{ bbb }{ ccc }

or:

$hash{aaa}{bbb}{ccc}

and not worry about whether the subscripts are reserved words. So this:

$hash{ shift }

is interpreted as $hash{"shift"}. You can force interpretation as a reserved word by adding anything that makes it more than a mere identifier:

$hash{  shift()  }
$hash{ +shift   }
$hash{  shift @_ }

References Don't Work as Hash Keys

Hash keys are stored internally ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required