← Back to Perl Course | Chapter 6: References | Lesson 3 of 7

Hash references

A hash reference is a handy way to carry a group of named values together.

In this page:

  1. Hash references

Hash references

Make one with \%hash or with the anonymous constructor { key => value }. Get a value with $ref->{key}, and get all keys with keys %$ref. Hash references are the usual way to represent records, and they can be passed to functions as a single argument.

Note: Use the exists function with the arrow, as in exists $ref->{key}, to test a key without creating it.

Example: Hash references

perl
use strict;
use warnings;

my %config = (host => "localhost", port => 8080);
my $href = \%config;
$href->{debug} = 1;
print "host: $href->{host}\n";
print "original sees debug: $config{debug}\n";
my $person = { name => "Grace", langs => 2 };
for my $key (sort keys %$person) {
    print "$key = $person->{$key}\n";
}
print "has email? ", (exists $person->{email} ? "yes" : "no"), "\n";
my @copy_keys = sort keys %{$href};
print "keys: @copy_keys\n";

# Output:
# host: localhost
# original sees debug: 1
# langs = 2
# name = Grace
# has email? no
# keys: debug host port
Common Mistakes
  1. Confusing the anonymous hash braces with a code block
  2. Writing %ref->{key} instead of $ref->{key}
  3. Forgetting that a hash reference must be dereferenced to use keys
Chapter Summary
  • { ... } creates an anonymous hash reference
  • $ref->{key} reads a value
  • keys %$ref lists keys
  • References make good records
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.