Constructing Records
Problem
You want to create a record data type.
Solution
Use a reference to an anonymous hash.
Discussion
Suppose you wanted to create a data type that contained various data
fields, akin to a C struct or a Pascal RECORD. The
easiest way is to use an anonymous hash. For example, here’s
how to initialize and use that record:
$record = {
NAME => "Jason",
EMPNO => 132,
TITLE => "deputy peon",
AGE => 23,
SALARY => 37_000,
PALS => [ "Norbert", "Rhys", "Phineas"],
};
printf "I am %s, and my pals are %s.\n",
$record->{NAME},
join(", ", @{$record->{PALS}});Just having one of these records isn’t much fun—
you’d like to build larger structures. For example, you might
want to create a %ByName hash that you could
initialize and use this way:
# store record
$byname{ $record->{NAME} } = $record;
# later on, look up by name
if ($rp = $byname{"Aron"}) { # false if missing
printf "Aron is employee %d.\n", $rp->{EMPNO};
}
# give jason a new pal
push @{$byname{"Jason"}->{PALS}}, "Theodore";
printf "Jason now has %d pals\n", scalar @{$byname{"Jason"}->{PALS}};That makes %byname a hash of hashes, because its
values are hash references. Looking up employees by name would be
easy using such a structure. If we find a value in the hash, we store
a reference to the record in a temporary variable,
$rp, which we then use to get any field we want.
We can use our existing hash tools to manipulate
%byname. For instance, we could use the
each iterator to loop through it in an arbitrary
order:
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access