References :: creating

References can be created in several ways:

  1. By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates another reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples:

             $scalarref = \$foo;
             $arrayref  = \@ARGV;
             $hashref   = \%ENV;
             $coderef   = \&handler;
    
  2. A reference to an anonymous array can be created using square brackets:

             $arrayref = [
                           'Laurel',
                           'Hardy',
                           ['Gummo', 'Zeppo', 'Chico']
                         ];
    

    The array has no name; it can only be accessed via its reference, $arrayref. Hence the reason it's called "anonymous."

  3. A reference to an anonymous hash can be created using curly braces:

             $hashref = {
                          'AC1'  => q[Asheron's Call],
                          'ACDM' => q[Asheron's Call],
                          'AC2'  => q[Asheron's Call 2],
                        };
    

    As with the array in the preceding example, the hash has no name; it can only be accessed via its reference, $hashref.

  4. A reference to an anonymous subroutine can be created using sub without a subroutine name:

             $coderef = sub { print "Who is Mattie Young?\n" }; 
    

    This subroutine can be called only via its reference, $coderef:

     1        # call anonymous subroutine via its reference
     2        &$coderef($arg);
     3