next up previous contents index
Next: Complex data structures Up: References and Complex Data Previous: References and Complex Data   Contents   Index


References

Before discussing complex data structures, we first introduce in what is known in Perl as references (these have some qualitative similarities to pointers in C). A reference is a scalar object, and can constructed using the backslash operator \ as
  my $x = 2;
  my $xref = \$x;
Here, $xref will be a reference to the scalar $x. References can similarly be made to arrays:
  my @a = (1, 3, 5);
  my $aref = \@a;
and to hashes:
  my %h = (age => 33, name => 'Elizabeth');
  my $href = \%h;
It is also possible to construct such references directly. For arrays, one uses square brackets as
  my $aref = [1, 3, 5];
while for hashes curly brackets are used:
  my $href = {age => 33, name => 'Elizabeth'};

Dereferencing a reference (finding out what it's value is) requires a special syntax. For scalar variables, one uses a double dollar sign as

  my $x = 2;
  my $xref = \$x;
  print qq{The value of \$\$xref is }, $$xref;
For accessing array and hash elements of references, a double dollar sign can also be used:
  my $aref = [1, 3, 5];
  print qq{The value of \$aref[2] is }, $$aref[2];

  my $href = {age => 33, name => 'Elizabeth');
  print qq{The value of \$href{age} is }, $$href{age};
However, this notation isn't very readable. Accessing array and hash elements can also be done with the arrow notation ->, as
  my $aref = [1, 3, 5];
  print qq{The value of \$aref[2] is }, $aref->[2];

  my $href = {age => 33, name => 'Elizabeth'};
  print qq{The value of \$href{age} is }, $href->{age};
Loops over all elements of array references can be constructed using the following syntax:
  my $aref = [1, 3, 5];
  for my $element (@$aref) {
    print qq{$element\n};
  }
where the @ symbol in @$aref forces the array reference $aref into an array context. A similar syntax exists for hashes:
  my $href = {age => 33, name => 'Elizabeth'};
  for my $key (keys %$href) {
    print qq{The key $key has value $href->{$key}\n};
  }
where the % symbol in %$href forces the hash reference $href into a hash context.

To see one aspect of the behaviour of references, consider

my $x = 4;
my $xref = \$x;
print "\$x is now $x, and \$xref has a value $$xref\n";

$x = 5;
print "\$x is now $x, and \$xref has a value $$xref\n";
When run, this prints out
$x is now 4, and $xref has a value 4
$x is now 5, and $xref has a value 5
Thus, when $x changes its value, the reference $xref also changes it's value. This is a fundamental property of references in general which we shall see used in many different contexts.
next up previous contents index
Next: Complex data structures Up: References and Complex Data Previous: References and Complex Data   Contents   Index