References

  • A reference is a scalar value, preceded by $
  • Can use references to build lists and hashes within lists and hashes

Getting a reference value

  • \  : Precede a variable name with a blackslash to get a reference value for the variable; the value can then be assigned to a reference variable.

Number

$num = 10;
$num_ref = \$num; # Reference to a named number (scalar)
$num_ref = \10;                   # Reference to an anonymous number (scalar)

String

$str = "Hello";
$str_ref = \$str; # Reference to a named string (scalar)
$ref = \"Hello";                  # Reference to an anonymous string (scalar)

Array

@arr = ('one', 'two');
$arr_ref = \@arr; # Reference to a named array
$arr_ref = ['one', 'two'];        # Reference to an anonymous array
@arr = ('one', 'two');
$arr_ref = [@arr]; # Reference to an anonymous copy of a named array

Hash

%hash = (
two => 'deux',
three => 'trois',
);
$hash_ref = \%hash; # Reference to a named hash
$hash_ref = {                     # Reference to an anonymous hash
two => 'deux',
three => 'trois',
};
%hash = (
two => 'deux',
three => 'trois',
);
$hash_ref = {%hash}; # Reference to an anonymous copy of a named hash

Dereference operator

  • ->  : Used for references to arrays and hashes to get the value that the reference refers to (like dereferencing a pointer to a struct or object in C / C++)

Dereferencing numerics and strings

  • If $ref is a reference to a simple scalar variable, $$ref or ${$ref} can be used anywhere the name of the scalar variable would be used (the braces are optional).
With out a      Substitution       Substitution
reference with braces without braces
---------- ------------ --------------
$int ${$int_ref} $$int_ref
$str ${$str_ref} $$str_ref

Dereferencing arrays and hashes

  • If $ref is a reference to an array or hash, {$ref} or ref-> can be used anywhere the name of the array or hash would be used (the braces are optional).
With out a    Dereference        Substitution          Substitution
reference operator with braces without braces
---------- ----------- ------------ --------------
@arr @{$arr_ref} @$arr_ref

%hash1 %{$hash1_ref} %$hash1_ref

$arr[3] $arr_ref->[3] ${$arr_ref}[3] $$arr_ref[3]
$hash1{red} $hash1_ref->{red} ${$hash1_ref}{red} $$hash1_ref{red}

Multiple levels of indirection

$ref = \"Hello";
$str = $$ref;
$ref_ref = \\"Hello";
$str2 = $$$ref_ref;

Resources URL: 
notes/perl/resources
Sources URL: 
notes/perl/sources

See Also