Generation of a Hash of Complex Records
Because Perl is quite good at parsing complex data structures, you might just put
your data declarations in a separate file as regular Perl code, and
then load them in with the do or
require built-in functions.
Another popular approach is to use a CPAN module (such as XML::Parser) to load in arbitrary data structures expressed in
some other language (such as XML).
You can build data structures piecemeal:
$rec = {};
$rec–>{series} = "flintstones";
$rec–>{nights} = [ find_days() ];Or read them in from a file (here, assumed to be in field=value syntax):
@members = ();
while (<>) {
%fields = split /[\s=]+/;
push @members, { %fields };
}
$rec–>{members} = [ @members ];And fold them into larger data structures keyed by one of the subfields:
$TV{ $rec–>{series} } = $rec;You can use extra pointer fields to avoid duplicate data. For
example, you might want a "kids"
field included in a person’s record, which might be a reference to
an array containing references to the kids’ own records. By having
parts of your data structure refer to other parts, you avoid the
data skew that would result from updating the data in one place but
not in another:
for $family (keys %TV) {
my $rec = $TV{$family}; # temporary pointer
@kids = ();
for $person ( @{$rec–>{members}} ) {
if ($person–>{role} =~ /kid|son|daughter/) {
push @kids, $person;
}
}
# $rec and $TV{$family} point to same data!
$rec–>{kids} = [ @kids ];
}The $rec–>{kids} = [ @kids
] assignment copies the array ...
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