"Perl for Perl Newbies" - Part 2ReferencesDereferencing

10.6. Dereferencing

The entire scalar or data structure pointed to by the reference can be retrieved by dereferencing. Dereferencing is done by using a $, a @ or a % (depending if the reference refers to a scalar , array or a hash respectively), and then the reference inside curly braces.

Here are some simple examples:

use strict;
use warnings;

my $ds1 =
    'h' => [5,6,7],
    'y' => { 't' => 'u', 'o' => 'p' },
    'hello' => 'up',

my $array_ref = [5, 6, 7, 10, 24, 90, 14];
my $x = "Hello World!";
my $y = \$x;

print "\$array_ref:\n";

print join(", ", @{$array_ref}), "\n";

print "\n\n\$ds1->{'h'}:\n";

print join(", ", @{$ds1->{'h'}}), "\n";

my %hash = %{$ds1->{'y'}};

print "\n\n\%hash:\n";

foreach my $k (keys(%hash))
    print $k,  " => ", $hash{$k};

print "\n\n\$\$y:\n";

print ${$y}, "\n";

If the expression that yields the reference is a simple one than the curly brackets can be omitted (e.g: @$array_ref or $$ref). However, assuming you use curly brackets - the expression surrounded inside them can be as complex as you would like.

Written by Shlomi Fish