start page | rating of books | rating of authors | reviews | copyrights

Perl Cookbook

Perl CookbookSearch this book
Previous: 11.4. Taking References to Functions Chapter 11
References and Records
Next: 11.6. Creating Arrays of Scalar References
 

11.5. Taking References to Scalars

Problem

You want to create and manipulate a reference to a scalar value.

Solution

To 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 ${...} to dereference:

print ${ $scalar_ref };       # dereference it ${ $scalar_ref } .= "string"; # alter referent's value

Discussion

If 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 sort , and the reference argument to bless . Because of this, you can only dereference a scalar reference by prefacing it with $ to get at its contents:

$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 $array[0] and $array[1] . If we tried to say $$array[0] , the tight binding of dereferencing would turn it into $array->[0] . It would treat $array as an array reference and return the element at index zero.

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 ref built-in to inspect a reference for its referent's type. Calling ref on a scalar reference returns the string " SCALAR ":

# check whether $someref contains a simple scalar reference if (ref($someref) ne 'SCALAR') {     die "Expected a scalar reference, not $someref\n";







 }

See Also

Chapter 4 of Programming Perl and perlref (1)


Previous: 11.4. Taking References to Functions Perl Cookbook Next: 11.6. Creating Arrays of Scalar References
11.4. Taking References to Functions Book Index 11.6. Creating Arrays of Scalar References

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.