Search code examples
perlcurly-braces

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?


Solution

  • 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];
    

    Update: Something I forgot to mention originally - the expression has to be enclosed in braces as it is a block of code that returns an array reference. It doesn't have to be a single expression. You could (but probably shouldn't!) write code like this:

    print ${
      my @arefs = $object->array_generator;
      my $aref = $arefs[1];
      $aref;
    }[0];