Hash references
A hash reference is a handy way to carry a group of named values together.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing the anonymous hash braces with a code block
- Writing %ref->{key} instead of $ref->{key}
- 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: