Using the Arrow Operator
For references to arrays, hashes, or subroutines, a third method of
dereferencing involves the use of the –> infix operator. This form of
syntactic sugar makes it easier to get at individual array or hash
elements, or to call a subroutine indirectly.
The type of the dereference is determined by the right operand―that is, by what follows directly after the arrow. If the next thing after the arrow is a bracket or brace, the left operand is treated as a reference to an array or a hash, respectively, to be subscripted by the expression on the right. If the next thing is a left parenthesis, the left operand is treated as a reference to a subroutine, to be called with whatever parameters you supply in the parentheses on the right.
Each of these next trios is equivalent, corresponding to the three notations we’ve introduced. (We’ve inserted some spaces to line up equivalent elements.)
$ $arrayref [2] = "Dorian"; #1
${ $arrayref }[2] = "Dorian"; #2
$arrayref–>[2] = "Dorian"; #3
$ $hashref {KEY} = "F#major"; #1
${ $hashref }{KEY} = "F#major"; #2
$hashref–>{KEY} = "F#major"; #3
& $coderef (Presto => 192); #1
&{ $coderef }(Presto => 192); #2
$coderef–>(Presto => 192); #3You can see that the initial sigil is missing from the third notation in each trio. The sigil is guessed at by Perl, which is why it can’t be used to dereference complete arrays, complete hashes, or slices of either. As long as you stick with scalar values, though, you can use any expression to the left ...
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