## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 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 } = 6.02e23;
\${ \$array } = "avocado";
print "\@array contains: ", join(", ", map { \$\$_ } @array ), "\n";```

Notice we have to put braces around `\$array` and `\$array`. If we tried to say `\$\$array`, the tight binding of dereferencing would turn it into `\$array-> ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required