Other Tricks You Can Do with Hard References
As mentioned earlier, the backslash operator is usually used on a single referent to generate a single reference, but it doesn’t have to be. When used on a list of referents, it produces a list of corresponding references. The second line of the following example does the same thing as the first line, since the backslash is automatically distributed throughout the whole list:
@reflist = (\$s, \@a, \%h, \&f); # List of four references @reflist = \($s, @a %h, &f); # Same thing
If a parenthesized list contains exactly one array or hash, then all of its values are interpolated, and references to each are returned:
@reflist = \(@x); # Interpolate array, then get refs
@reflist = map { \$_ } @x; # Same thingThis also occurs when there are internal parentheses:
@reflist = \(@x, (@y)); # But only single aggregates expand
@reflist = (\@x, map { \$_ } @y); # Same thingIf you try this with a hash, the result will contain references to the values (as you’d expect), but also references to copies of the keys (as you might not expect).
Since array and hash slices are really just lists, you can backslash a slice of either of these to get a list of references. Each of the next three lines does exactly the same thing:
@envrefs = \@ENV{"HOME", "TERM"}; # Backslashing a slice
@envrefs = \( $ENV{HOME}, $ENV{TERM} ); # Backslashing a list
@envrefs = ( \$ENV{HOME}, \$ENV{TERM} ); # A list of two referencesSince functions can return lists, you can apply a backslash ...
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