References

References are at the core of powerful and advanced Perl usage. Though they sound tricky they are not. Well.... not that tricky! ;-) I recommend you just learn them, and try to use them whenever you can to learn them.

A reference is a scalar value that contains an internal pointer to the actual data. Using references, multiple references can be used to point to the same data, and when the underlying data changes, it is available to every reference of it.

With References, you can

  • Pass a reference to large array or hash as a single value instead of having Perl copy the whole structure in the parameter list.
  • Pass a reference to subroutines which would modify the value directly.
  • References are used to build complex data sructures. More on that later.
$r = \$name; # Reference to a scalar (string)
print $$r; # Dereferencing to print the value;
 
$r = \@array; # Array reference
$r = \(1, 2, 3); # Refererence to a list
$r = [1, 2, 3]; # Same as above, preferred notation
print @$r; # Accessing the array
print @{$r}; # Alternate syntax, useful when using an expression
print $$r[0]; # Accessing a single element
print $r->[0]; # Alternate syntax, I prefer this one
 
$r = \%hash; # Hash reference
$r = \(key1=>1, key2=>2); # Referencing an anonymous hash
$r = {Key1=>1, key2=>2}; # Preferred, alternate syntax
 
$r = \*STDIN; # Reference to the Standard-Input File Glob;
 
$r = \&mysub; # Takes reference to a subroutine
$r = sub { $x=1; }; # Reference to anonymous subroutine
 
$r = \$reference; # Reference to a reference!
 
print ref($r); # Prints 'SCALAR' for reference to a scalar
print ref($r); # Prints 'REF' for reference to a reference
print ref($r); # Prints 'ARRAY' if var/expression is an array reference
print ref($r); # Prints 'HASH' if var/expression is a hash reference
print ref($r); # Prints 'CODE' if it is a subroutine reference
print ref($r); # Prints classname if it is an object reference (typeof)
print ref($s); # Prints '' if it is a scalar, not a reference (False)
 
programming/perl/references.txt · Last modified: 2005/07/18 17:10 by allen