introduction to Perl 5 for web developers Dereferencing a Reference Once you have created a reference, you will need to get at the value that the reference holds. However, recall that references hold "pointers" to memory slots. So if you simply access the value of the reference, you probably won’t get what you want.

Consider the following case:

     #!/usr/bin/perl -wT
     use strict;
     my $my_scalar = "Selena Sol";
     my @my_array = ("1", "2", "3");
     my $scalar_reference = \$my_scalar;
     my $array_reference = \@my_array;
     print "$scalar_reference\n" .
            "$array_reference\n";

Check out the results! Notice that for $scalar_reference, Perl prints out the odd looking value "SCALAR(Ox1011e9e8)" instead of "Selena Sol".

[Example 1]

Well, Perl is doing the requested thing, of course and printing out the value of the reference that corresponds to a location in memory where the contents of $my_scalar are actually held.

Of course, it is most likely that what you really want is the value the reference is pointing to. Basically, to get this value, you must "dereference" the reference.

Dereferencing scalar, array, hash and subroutine references follow a very similar pattern as exemplified below:

     #!/usr/bin/perl -wT
     use strict;
     my $my_scalar = "Selena Sol";
     my @my_array  = ("1", "2", "3");
     my %my_hash   = {'NAME' => 'Gunther',}
     my $scalar_reference = \$my_scalar;
     my $array_reference  = \@my_array;
     my $hash_reference   = \%my_hash;

     print "$$scalar_reference\n" .
           "@$array_reference[0]\n" .
	   "$hash_reference->{'NAME'}\n";

Notice that we use an extra $ and @ in the case of dereferencing scalars and arrays, and that we use the -> for hashes. Check out the results of this little program:

[Example 2]

Finally, a subroutine reference can be dereferenced using an "&" before the reference name such as:

     #!/usr/bin/perl -wT
     use strict;
     sub print_message {
	    my ($string) = @_;
        print "$string\n";
     }
     my $subroutine_reference = \&print_message;
     $subroutine_reference->("Hello Cyberspace");
Previous | Next | Table of Contents