11.5. Taking References to ScalarsProblemYou want to create and manipulate a reference to a scalar value. SolutionTo create a reference to a scalar variable, use the backslash operator: $scalar_ref = \$scalar; # get reference to named scalar To create a reference to an anonymous scalar value (a value that isn't in a variable), assign through a dereference of an undefined variable: undef $anon_scalar_ref; $$anon_scalar_ref = 15; This creates a reference to a constant scalar: $anon_scalar_ref = \15;
Use print ${ $scalar_ref }; # dereference it ${ $scalar_ref } .= "string"; # alter referent's value DiscussionIf you want to create many new anonymous scalars, use a subroutine that returns a reference to a lexical variable out of scope, as explained in the Introduction: sub new_anon_scalar { my $temp; return \$temp; }
Perl almost never implicitly dereferences for you. Exceptions include references to filehandles, code references to $sref = new_anon_scalar(); $$sref = 3; print "Three = $$sref\n"; @array_of_srefs = ( new_anon_scalar(), new_anon_scalar() ); ${ $array[0] } = 6.02e23; ${ $array[1] } = "avocado"; print "\@array contains: ", join(", ", map { $$_ } @array ), "\n";
Notice we have to put braces around Here are other examples where it is safe to omit the braces: $var = `uptime`; # $var holds text $vref = \$var; # $vref "points to" $var if ($$vref =~ /load/) {} # look at $var, indirectly chomp $$vref; # alter $var, indirectly
As mentioned in the introduction, you may use the # check whether $someref contains a simple scalar reference if (ref($someref) ne 'SCALAR') { die "Expected a scalar reference, not $someref\n"; } See AlsoChapter 4 of Programming Perl and perlref (1) Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|