Ltf4an Ltf4an - 8 months ago 55
Perl Question

What is the role of the curly brace in this case in Perl?

The following print statements are valid in accessing the 1st element of the array reference

my $aref = [6, 7, 8];
print $aref->[0];
print $$aref[0];
print ${$aref}[0];

What is the reason for allowing/using the curly brace in the 3rd print? Does it work by design or by chance?

Answer Source

The reason is that the expression inside the braces can be arbitrarily complex. Imagine, for example, that you had an object with a method that returned a list of array references - and that you wanted to use the second reference in that list. Then you could use the following code:

print ${ ($obj->array_generator)[1] }[0];

Inside the braces you can use any expression that returns an array reference. It is only in the simple case (where the expression is a simple scalar variable) that you can omit the braces.

Of course, using this syntax to look up elements in the referenced array is rarely a good idea - I'd always recommend the arrow syntax instead.

print +($obj->array_generator)[1]->[0];