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] ...

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.