ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
11.6. Creating Arrays of Scalar ReferencesProblemYou 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. SolutionTo 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 DiscussionIn the following examples, ($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 Here's how to deal with such an array without explicit indexing. use Math::Trig qw(pi); # load the constant pi foreach $sref (@array) { # prepare to change $a,$b,$c,$d ($$sref **= 3) *= (4/3 * pi); # replace with spherical volumes } This code uses the formula for deriving the volume of a sphere: The Actually, anonymous scalars are pretty useless, given that a scalar value fits in the same space as a scalar reference. That's why there's no explicit composer. Scalar references exist only to allow aliasing - which can be done in other ways. See AlsoThe section on "Assignment Operators" in Chapter 2 of Programming Perl and in perlop (1) |