References

A compound variable (array, hash) can have the full compund form such as @array or %hash. But it can also be referred to by a scalar reference, which is like a pointer.

This is useful when e.g. making an array with arrays in it: the "inner" arrays should be references. Or a list of hashes: the "inner" hashes are refs.

Compound to Reference Conversion

To convert a %hash or a @array to a reference, you can use either:

Reference to Compound Conversion

Conversion Example

 # Map of names to email addresses
 my %staff = ( Jason => 'jason@example.com',
               Peter => 'peter@example.com' );

 # Convert to a reference
 my $hashref = \%staff;

 # Expand to a different hash
 my %expanded = %{ $hashref };
 for my $name (keys(%expanded)) {
    print("$name has email $expanded{$name}\n");
 }

Quick Expansions

Initializing a hashref or an arrayref

Arrays or hashes are initialized as:

 my @array = (1, 2, 3);
 my %hash  = (a => 1, b => 2, c => 3);

References can also be defined and initialized at the same time, but they require { and }, or [ and ], instead of ( and ):

 # Array reference: [ ... ]
 my $arrayref = [ 1, 2, 3 ];

 # Hash reference: { ... }
 my $hashref  = { a => 1, b => 2, c => 3 };

Exercise

Given the following three compound data structures:

 # structure 1
 ( username => 'karel',
   data     => { fullname => 'Karel Kubat',
                 email => 'karel@kubat.nl' } )

 # structure 2
 ( username => 'harry',
   data     => { fullname => 'Harry Kodden',
                 email => 'harry@kodden.com' } )

 # structure 3
 ( username => 'martijn',
   data     => { fullname => 'Martijn van der Molen',
                 email => 'mkvdmolen@gmail.com' } )