Using a block As a Variable Name
Not only can you dereference a simple variable name, you can also
dereference the contents of a BLOCK.
Anywhere you’d put an alphanumeric identifier as part of a variable
or subroutine name, you can replace the identifier with a
BLOCK returning a reference of the
correct type. In other words, the earlier examples could all be
disambiguated like this:
$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = "January";
@{$arrayref}[4..6] = qw/May June July/;
${$hashref}{"KEY"} = "VALUE";
@{$hashref}{"KEY1","KEY2"} = ("VAL1","VAL2");
&{$coderef}(1,2,3);not to mention:
$refrefref = \\\"howdy";
print ${${${$refrefref}}};Admittedly, it’s silly to use the braces in these simple
cases, but the BLOCK can contain any
arbitrary expression. In particular, it can contain subscripted
expressions. In the following example, $dispatch{$index} is assumed to contain a
reference to a subroutine (sometimes called a “coderef”). The
example invokes the subroutine with three arguments:
&{ $dispatch{$index} }(1, 2, 3);Here, the BLOCK is necessary.
Without that outer pair of braces, Perl would have treated $dispatch as the coderef instead of
$dispatch{$index}.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access