What's the difference between a hash and hash reference in Perl?

This program illustrates the difference between a hash and a hash reference in Perl.

#!/usr/bin/perl
use warnings;
use strict;

# This is a hash

my %hash = (
    onions => 1,
    potatoes => 4,
    carrots => 8,
);

# Print a value.

print "Step one: put some values in a hash.\n";
print "There are $hash{onions} onions.\n";

# Copy the hash.

my %veg = %hash;

# Change a value.

$veg{onions} = 42;

# Now print the number of onions.

print "Step two: copy the hash.\n";
print "There are $hash{onions} onions in \%hash.\n";
print "There are $veg{onions} onions in \%veg.\n";

# This is a hash reference.

my $hash_ref = \%veg;

# Change a value.

$hash_ref->{onions} = 999999;

# Print all the values.

# Now print the number of onions.

print "Step three: make a reference to a hash.\n";
print "There are $hash{onions} onions in \%hash.\n";
print "There are $veg{onions} onions in \%veg.\n";
print "There are $hash_ref->{onions} onions in what \$hash_ref points to.\n";

# Now change what $hash_ref points to.

$hash_ref = \%hash;

# Now print the number of onions again.

print "Step four: change what the reference points to.\n";
print "There are $hash{onions} onions in \%hash.\n";
print "There are $veg{onions} onions in \%veg.\n";
print "There are $hash_ref->{onions} onions in what \$hash_ref points to.\n";

(download)

This program prints out the following output:

Step one: put some values in a hash.
There are 1 onions.
Step two: copy the hash.
There are 1 onions in %hash.
There are 42 onions in %veg.
Step three: make a reference to a hash.
There are 1 onions in %hash.
There are 999999 onions in %veg.
There are 999999 onions in what $hash_ref points to.
Step four: change what the reference points to.
There are 1 onions in %hash.
There are 999999 onions in %veg.
There are 1 onions in what $hash_ref points to.

Web links


Copyright © Ben Bullock 2009-2019. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer