# Recipe 11.5 Taking References to Scalars

#### 11.5.1 Problem

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

#### 11.5.2 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 to a dereferenced 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```

#### 11.5.3 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 this chapter's Introduction:

```sub new_anon_scalar {
my \$temp;
return \\$temp;
}```

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

Notice we 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";
}```

Chapters 8 and 9 of Programming Perl and perlref(1)

 Chapter 1. Strings
 Chapter 2. Numbers
 Chapter 3. Dates and Times
 Chapter 4. Arrays
 Chapter 5. Hashes
 Chapter 6. Pattern Matching
 Chapter 7. File Access
 Chapter 8. File Contents
 Chapter 9. Directories
 Chapter 10. Subroutines
 Chapter 12. Packages, Libraries, and Modules
 Chapter 13. Classes, Objects, and Ties
 Chapter 14. Database Access
 Chapter 15. Interactivity
 Chapter 16. Process Management and Communication
 Chapter 17. Sockets
 Chapter 18. Internet Services
 Chapter 19. CGI Programming
 Chapter 20. Web Automation
 Chapter 21. mod_perl
 Chapter 22. XML