Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

\* - Creating Hard References

This section describes what is a hard reference, and how to create hard references with the reference operator, \ on variables, functions, and anonymous objects.

Hard references are pointers (or addresses) of other variables, functions, or any objects. Hard references are stored in scalar variables. They can be created in several ways.

1. Using the backslash operator, \, on a variable or a function to create a hard reference for that variable or function, as in the following examples:

   $r1 = \$a;
   $r2 = \@b;
   $r3 = \%c;
   $r4 = \&d;

There are three special usages of the backslash operator, \:

1.1. Using the backslash operator, \, on an expression that returns a scalar to create a hard reference to an anonymous scalar (not assigned to any variable name), as in the following examples:

   $r1 = \1;
   $r2 = \'foo';
   $r3 = \(1+1);

1.2. Using the backslash operator, \, on an list object enclosed in parentheses to create a list of hard references to all elements in the list object, as in the following examples:

   @r1 = \(Mon, Tue, Wed); # same as (\'Mon',\'Tue',\'Wed')
   @r2 = \(@b); # not the same as \@b

1.3. Using the backslash operator, \, on a hard reference to create a hard reference of the specified hard reference, as in the following examples:

   $r1 = \$a;
   $r2 = \$r1;
   $r3 = \\\%c;

2. Using square brackets on a list object to create a hard reference for an anonymous array (not assigned to any variable name), as in the following examples:

   $r1 = [3,5,7,11];
   $r2 = [Mon, Tue, Wed];
   $r3 = ['Jan',31,'Feb',28,'Mar',31];

3. Using curly brackets on a list object to create a hard reference for an anonymous hash (not assigned to any variable name), as in the following examples:

   $r1 = {3,5,7,11}; # not very useful
   $r2 = {Mon, Tue, Wed}; # not very useful
   $r3 = {'Jan',31,'Feb',28,'Mar',31};

4. Using "sub" without a name to create a hard reference for an anonymous function (not assigned to any function name), as in the following examples:

   $r1 = sub {print "I am here.\n";}

Sections in This Chapter

\* - Creating Hard References

Using Hard References

$$name - Replacing Identifiers by Scalar Variables

${EXPR} - Replacing Identifiers by Expressions

EXPR->* - The Dereference Operator

$$$name - Nested Hard References

\$b-\$a - Using Hard References in Other Operations

Dr. Herong Yang, updated in 2008
\* - Creating Hard References