Creating Arrays of Scalar References
Problem
You want to create and manipulate an array of references to scalars. This arises when you pass variables by reference to a function to let the function change their values.
Solution
To create an array, either backslash each scalar in the list to store in the array:
@array_of_scalar_refs = ( \$a, \$b );
or simply backslash the entire list, taking advantage of the backslash operator’s distributive property:
@array_of_scalar_refs = \( $a, $b );
To get or set the value of an element of the list, use
${
...
}
:
${ $array_of_scalar_refs[1] } = 12; # $b = 12
Discussion
In the following examples, @array
is a simple
array containing references to scalars (an array of references is not
a reference to an array). To access the original data indirectly,
braces are critical.
($a, $b, $c, $d) = (1 .. 4); # initialize @array = (\$a, \$b, \$c, \$d); # refs to each scalar @array = \( $a, $b, $c, $d); # same thing! @array = map { \my $anon } 0 .. 3; # allocate 4 anon scalarresf ${ $array[2] } += 9; # $c now 12 ${ $array[ $#array ] } *= 5; # $d now 20 ${ $array[-1] } *= 5; # same; $d now 100 $tmp = $array[-1]; # using temporary $$tmp *= 5; # $d now 500
The two assignments to @array
are equivalent
—the backslash operator is distributive across a list. So
preceding a list (not an array) with a backslash is the same as
applying a backslash to everything in that list. The ensuing code
changes the values of the variables whose references were stored in
the array.
Here’s ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.