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

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.