PERLDSC(1)

πŸ’– PERLDSC πŸ’–

okay so this is perldsc, the Perl Data Structures Cookbook β€” straight out of the Perl Programmers Reference Guide. yes bestie, we are reading a whole cookbook together. grab a snack πŸ“βœ¨


✨ DESCRIPTION ✨

Perl lets us have complex data structures. like, you can literally write this and boom β€” all of a sudden you've got an array with three dimensions, no cap:

for my $x (1 .. 10) {
    for my $y (1 .. 10) {
        for my $z (1 .. 10) {
            $AoA[$x][$y][$z] =
                $x ** $y + $z;
        }
    }
}

but alas 😭 however simple that looks, underneath it is a much more elaborate construct than meets the eye. it's giving iceberg energy.

so like... how do you print it out? why can't you just say print @AoA? how do you sort it? how can you pass it to a function, or get one of these back from a function? is it an object? can you save it to disk and read it back later? how do you access whole rows or columns of that matrix? do all the values have to be numeric?? so many questions πŸ’€

as you can see, it's quite easy to become confused. and while a small portion of the blame for that can be pinned on the reference-based implementation, honestly it's more about a lack of existing documentation with examples designed for the beginner. (that's us. we're the beginner. hi 🫢)

this document is meant to be a detailed but understandable treatment of the many different sorts of data structures you might want to develop. it should also serve as a cookbook of examples β€” so when you need to create one of these complex data structures, you can just pinch, pilfer, or purloin a drop-in example from here. iconic behaviour, honestly πŸ‘‘

let's look at each of these possible constructs in detail. there are separate sections on each of the following:

  • arrays of arrays
  • hashes of arrays
  • arrays of hashes
  • hashes of hashes
  • more elaborate constructs

but for now, let's look at general issues common to all these types of data structures.


πŸ¦‹ REFERENCES πŸ¦‹

the most important thing to understand about all data structures in Perl β€” including multidimensional arrays β€” is that even though they might appear otherwise, Perl @ARRAYs and %HASHes are all internally one-dimensional. they can hold only scalar values (meaning a string, number, or a reference). they cannot directly contain other arrays or hashes β€” instead they contain references to other arrays or hashes. periodt.

you can't use a reference to an array or hash in quite the same way that you would a real array or hash. for C or C++ programmers who aren't used to distinguishing between arrays and pointers to the same, this can be confusing. if that's you, just think of it as the difference between a structure and a pointer to a structure. 🧚

you can (and should) read more about references in perlref. briefly: references are rather like pointers that know what they point to. (objects are also a kind of reference, but we won't be needing them right away β€” if ever.) this means that when you have something which looks to you like an access to a two-or-more-dimensional array and/or hash, what's really going on is that the base type is merely a one-dimensional entity that contains references to the next level. it's just that you can use it as though it were a two-dimensional one. and actually, this is the way almost all C multidimensional arrays work as well. no cap.

$array[7][12]                       # array of arrays
$array[7]{string}                   # array of hashes
$hash{string}[7]                    # hash of arrays
$hash{string}{'another string'}     # hash of hashes

now, because the top level contains only references, if you try to print out your array with a simple print() function, you'll get something that doesn't look very nice, like this:

my @AoA = ( [2, 3], [4, 5, 7], [0] );
print $AoA[1][2];
 7
print @AoA;
ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)

that's because Perl doesn't (ever) implicitly dereference your variables. if you want to get at the thing a reference is referring to, then you have to do this yourself using either prefix typing indicators, like ${$blah}, @{$blah}, @{$blah[$i]}, or else postfix pointer arrows, like $arr->[3], $hash->{fred}, or even $obj->method()->[3].


πŸ’€ COMMON MISTAKES πŸ’€

the two most common mistakes made in constructing something like an array of arrays are: (1) accidentally counting the number of elements, or (2) taking a reference to the same memory location repeatedly. bestie, we've all been there πŸ™ˆ

here's the case where you just get the count instead of a nested array:

for my $i (1..10) {
    my @array = somefunc($i);
    $AoA[$i] = @array;      # WRONG!
}

that's just the simple case of assigning an array to a scalar and getting its element count. and if that's what you really and truly want, then you might do well to consider being a tad more explicit about it, like this:

for my $i (1..10) {
    my @array = somefunc($i);
    $counts[$i] = scalar @array;
}

and here's the case of taking a reference to the same memory location again and again:

# Either without strict or having an outer-scope my @array;
# declaration.

for my $i (1..10) {
    @array = somefunc($i);
    $AoA[$i] = \@array;     # WRONG!
}

so, what's the big problem with that? it looks right, doesn't it? after all, I just told you that you need an array of references, so by golly, you've made me one!

unfortunately, while this is true, it's still broken. all the references in @AoA refer to the very same place, and they will therefore all hold whatever was last in @array! it's similar to the problem demonstrated in the following C program:

#include <pwd.h>
main() {
    struct passwd *getpwnam(), *rp, *dp;
    rp = getpwnam("root");
    dp = getpwnam("daemon");

    printf("daemon name is %s\nroot name is %s\n",
            dp->pw_name, rp->pw_name);
}

which will print

daemon name is daemon
root name is daemon

the problem is that both rp and dp are pointers to the same location in memory! in C, you'd have to remember to malloc() yourself some new memory. in Perl, you'll want to use the array constructor [] or the hash constructor {} instead. here's the right way to do the preceding broken code fragments:

# Either without strict or having an outer-scope my @array;
# declaration.

for my $i (1..10) {
    @array = somefunc($i);
    $AoA[$i] = [ @array ];
}

the square brackets make a reference to a new array with a copy of what's in @array at the time of the assignment. this is what you want. chef's kiss πŸ’…

note that this will produce something similar:

# Either without strict or having an outer-scope my @array;
# declaration.
for my $i (1..10) {
    @array = 0 .. $i;
    $AoA[$i]->@* = @array;
}

is it the same? well, maybe so β€” and maybe not. πŸ‘€ the subtle difference is that when you assign something in square brackets, you know for sure it's always a brand new reference with a new copy of the data. something else could be going on in this new case with the $AoA[$i]->@* dereference on the left-hand-side of the assignment. it all depends on whether $AoA[$i] had been undefined to start with, or whether it already contained a reference. if you had already populated @AoA with references, as in

$AoA[3] = \@another_array;

then the assignment with the indirection on the left-hand-side would use the existing reference that was already there:

$AoA[3]->@* = @array;

of course, this would have the "interesting" effect of clobbering @another_array. (have you ever noticed how when a programmer says something is "interesting", that rather than meaning "intriguing", they're disturbingly more apt to mean that it's "annoying", "difficult", or both? :-)

so just remember: always use the array or hash constructors with [] or {}, and you'll be fine β€” although it's not always optimally efficient.

surprisingly, the following dangerous-looking construct will actually work out fine:

for my $i (1..10) {
    my @array = somefunc($i);
    $AoA[$i] = \@array;
}

that's because my() is more of a run-time statement than it is a compile-time declaration per se. this means that the my() variable is remade afresh each time through the loop. so even though it looks as though you stored the same variable reference each time, you actually did not! this is a subtle distinction that can produce more efficient code β€” at the risk of misleading all but the most experienced of programmers. so I usually advise against teaching it to beginners. in fact, except for passing arguments to functions, I seldom like to see the gimme-a-reference operator (backslash) used much at all in code. instead, I advise beginners that they (and most of the rest of us) should try to use the much more easily understood constructors [] and {} instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes.

note also that there exists another way to write a dereference! these two lines are equivalent:

$AoA[$i]->@* = @array;
@{ $AoA[$i] } = @array;

the first form, called postfix dereference, is generally easier to read, because the expression can be read from left to right, and there are no enclosing braces to balance. on the other hand, it is also newer. it was added to the language in 2014, so you will often encounter the other form, circumfix dereference, in older code.

in summary:

$AoA[$i] = [ @array ];     # usually best
$AoA[$i] = \@array;        # perilous; just how my() was that array?
$AoA[$i]->@* = @array;     # way too tricky for most programmers
@{ $AoA[$i] } = @array;    # just as tricky, and also harder to read

πŸ’… CAVEAT ON PRECEDENCE πŸ’…

okay bestie so when we're talking about stuff like "@{$AoA[$i]}", plot twist: these two things are literally the same thing:

$aref->[2][2]       # clear
$$aref[2][2]        # confusing

and the reason is kinda unhinged ngl. Perl's precedence rules for its five prefix dereferencers β€” which fr look like someone swearing: "$ @ * % &" β€” make them bind tighter than the postfix subscripting brackets or braces!! πŸ’€

so if you're coming from C or C++, this is gonna give you whiplash, because you're so used to *a[i] meaning "what's pointed to by the i'th element of a". like, you take the subscript first, then dereference the thing at that subscript. which is totally fine in C. but bestie… this is not C. 🫠

the seemingly-equivalent Perl construct $$aref[$i] does the deref of $aref first, making it take $aref as a reference to an array, then dereferences that, and only finally tells you the i'th value of the array pointed to by $AoA. so if you actually wanted the C notion, you could write "$AoA[$i]->$*" to explicitly dereference the i'th item, reading left to right. ✨


πŸŽ€ WHY YOU SHOULD ALWAYS "use VERSION" πŸŽ€

if all this is starting to sound scarier than it's worth β€” relax, babe. 🌸 Perl has features specifically designed to save you from its most common pitfalls.

one way to avoid getting confused is to start every program with:

use strict;

this way you're forced to declare all your variables with my() and it also disallows accidental "symbolic dereferencing". so if you'd done this:

my $aref = [
    [ "fred", "barney", "pebbles", "bambam", "dino", ],
    [ "homer", "bart", "marge", "maggie", ],
    [ "george", "jane", "elroy", "judy", ],
];

print $aref[2][2];

the compiler would immediately flag that as an error at compile time, because you were accidentally accessing @aref, an undeclared variable β€” and it would thereby remind you to write instead:

print $aref->[2][2]

and since Perl version 5.12, a "use VERSION" declaration will also enable the "strict" pragma. plus it enables a feature bundle, which gives you more useful features. and since version 5.36 it also enables the "warnings" pragma. πŸ’–

so like, the often-best way to activate all these things at once is to start a file with:

use v5.36;

that way every file starts with "strict", "warnings", and a bunch of useful named features all switched on β€” plus several older features being switched off (like "indirect"). for more info, see "use VERSION" in perlfunc. iykyk 🧚


πŸ” DEBUGGING πŸ”

you can use the debugger's "x" command to dump out complex data structures. for example, given the assignment to $AoA above, here's the debugger output:

DB<1> x $AoA
$AoA = ARRAY(0x13b5a0)
   0  ARRAY(0x1f0a24)
      0  'fred'
      1  'barney'
      2  'pebbles'
      3  'bambam'
      4  'dino'
   1  ARRAY(0x13b558)
      0  'homer'
      1  'bart'
      2  'marge'
      3  'maggie'
   2  ARRAY(0x13b540)
      0  'george'
      1  'jane'
      2  'elroy'
      3  'judy'

it's giving organized. it's giving tidy little tree. we love to see it πŸ‘‘


🌈 CODE EXAMPLES 🌈

presented with little comment here are short code examples illustrating access of various types of data structures. no fluff, just vibes and working code πŸ’…

πŸ¦‹ ARRAYS OF ARRAYS πŸ¦‹

✨ Declaration of an ARRAY OF ARRAYS ✨

my @AoA = (
       [ "fred", "barney" ],
       [ "george", "jane", "elroy" ],
       [ "homer", "marge", "bart" ],
     );

✨ Generation of an ARRAY OF ARRAYS ✨

# reading from file
while ( <> ) {
    push @AoA, [ split ];
}

# calling a function
for my $i ( 1 .. 10 ) {
    $AoA[$i] = [ somefunc($i) ];
}

# using temp vars
for my $i ( 1 .. 10 ) {
    my @tmp = somefunc($i);
    $AoA[$i] = [ @tmp ];
}

# add to an existing row
push $AoA[0]->@*, "wilma", "betty";

✨ Access and Printing of an ARRAY OF ARRAYS ✨

# one element
$AoA[0][0] = "Fred";

# another element
$AoA[1][1] =~ s/(\w)/\u$1/;

# print the whole thing with refs
for my $aref ( @AoA ) {
    print "\t [ @$aref ],\n";
}

# print the whole thing with indices
for my $i ( 0 .. $#AoA ) {
    print "\t [ $AoA[$i]->@* ],\n";
}

# print the whole thing one at a time
for my $i ( 0 .. $#AoA ) {
    for my $j ( 0 .. $AoA[$i]->$#* ) {
        print "elem at ($i, $j) is $AoA[$i][$j]\n";
    }
}

πŸ“ HASHES OF ARRAYS πŸ“

✨ Declaration of a HASH OF ARRAYS ✨

my %HoA = (
       flintstones        => [ "fred", "barney" ],
       jetsons            => [ "george", "jane", "elroy" ],
       simpsons           => [ "homer", "marge", "bart" ],
     );

✨ Generation of a HASH OF ARRAYS ✨

# reading from file
# flintstones: fred barney wilma dino
while ( <> ) {
    next unless s/^(.*?):\s*//;
    $HoA{$1} = [ split ];
}

# reading from file; more temps
# flintstones: fred barney wilma dino
while ( my $line = <> ) {
    my ($who, $rest) = split /:\s*/, $line, 2;
    my @fields = split ' ', $rest;
    $HoA{$who} = [ @fields ];
}

# calling a function that returns a list
for my $group ( "simpsons", "jetsons", "flintstones" ) {
    $HoA{$group} = [ get_family($group) ];
}

# likewise, but using temps
for my $group ( "simpsons", "jetsons", "flintstones" ) {
    my @members = get_family($group);
    $HoA{$group} = [ @members ];
}

# append new members to an existing family
push $HoA{flintstones}->@*, "wilma", "betty";

✨ Access and Printing of a HASH OF ARRAYS ✨

# one element
$HoA{flintstones}[0] = "Fred";

# another element
$HoA{simpsons}[1] =~ s/(\w)/\u$1/;

# print the whole thing
foreach my $family ( keys %HoA ) {
    print "$family: $HoA{$family}->@* \n"
}

# print the whole thing with indices
foreach my $family ( keys %HoA ) {
    print "family: ";
    foreach my $i ( 0 .. $HoA{$family}->$#* ) {
        print " $i = $HoA{$family}[$i]";
    }
    print "\n";
}

# print the whole thing sorted by number of members
foreach my $family ( sort { $HoA{$b}->@* <=> $HoA{$a}->@* } keys %HoA ) {
    print "$family: $HoA{$family}->@* \n"
}

# print the whole thing sorted by number of members and name
foreach my $family ( sort {
                           $HoA{$b}->@* <=> $HoA{$a}->@*
                                         ||
                                     $a cmp $b
           } keys %HoA )
{
    print "$family: ", join(", ", sort $HoA{$family}->@* ), "\n";
}

🌸 ARRAYS OF HASHES 🌸

✨ Declaration of an ARRAY OF HASHES ✨

my @AoH = (
       {
           Lead     => "fred",
           Friend   => "barney",
       },
       {
           Lead     => "george",
           Wife     => "jane",
           Son      => "elroy",
       },
       {
           Lead     => "homer",
           Wife     => "marge",
           Son      => "bart",
       }
 );

✨ Generation of an ARRAY OF HASHES ✨

# reading from file
# format: LEAD=fred FRIEND=barney
while ( <> ) {
    my $rec = {};
    for my $field ( split ) {
        my ($key, $value) = split /=/, $field;
        $rec->{$key} = $value;
    }
    push @AoH, $rec;
}

# reading from file
# format: LEAD=fred FRIEND=barney
# no temp
while ( <> ) {
    push @AoH, { split /[\s+=]/ };
}

# calling a function that returns a key/value pair list, like
# "lead","fred","daughter","pebbles"
while ( my %fields = getnextpairset() ) {
    push @AoH, { %fields };
}

# likewise, but using no temp vars
while (<>) {
    push @AoH, { parsepairs($_) };
}

# add key/value to an element
$AoH[0]{pet} = "dino";
$AoH[2]{pet} = "santa's little helper";

✨ Access and Printing of an ARRAY OF HASHES ✨

# one element
$AoH[0]{lead} = "fred";

# another element
$AoH[1]{lead} =~ s/(\w)/\u$1/;

# print the whole thing with refs
for my $href ( @AoH ) {
    print "{ ";
    for my $role ( keys %$href ) {
        print "$role=$href->{$role} ";
    }
    print "}\n";
}

# print the whole thing with indices
for my $i ( 0 .. $#AoH ) {
    print "$i is { ";
    for my $role ( keys $AoH[$i]->%* ) {
        print "$role=$AoH[$i]{$role} ";
    }
    print "}\n";
}

# print the whole thing one at a time
for my $i ( 0 .. $#AoH ) {
    for my $role ( keys $AoH[$i]->%* ) {
        print "elem at ($i, $role) is $AoH[$i]{$role}\n";
    }
}

πŸ’– HASHES OF HASHES πŸ’–

Okay bestie, this is the one. A hash of hashes. A hash where every value is also a whole hash. It's giving nesting-doll energy, it's giving "I contain multitudes", it's lowkey the most useful data structure in all of Perl and I will not be taking questions. 🫢

🌸 Declaration of a HASH OF HASHES 🌸

Just... build it. Inline. Like a boss.

my %HoH = (
       flintstones => {
               lead      => "fred",
               pal       => "barney",
       },
       jetsons     => {
               lead      => "george",
               wife      => "jane",
               "his boy" => "elroy",
       },
       simpsons    => {
               lead      => "homer",
               wife      => "marge",
               kid       => "bart",
       },
);

See how "his boy" is in quotes? That's because it has a space in it, bestie. Bareword keys only work when they're plain identifiers. The audacity of whitespace, honestly. 😭


✨ Generation of a HASH OF HASHES ✨

Okay so you don't always get to just type it out. Sometimes you gotta build it from data. Here's every way, no cap.

Reading from a file, the tight way:

# reading from file
# flintstones: lead=fred pal=barney wife=wilma pet=dino
while ( <> ) {
    next unless s/^(.*?):\s*//;
    my $who = $1;
    for my $field ( split ) {
        my ($key, $value) = split /=/, $field;
        $HoH{$who}{$key} = $value;
    }
}

Same thing but with a temp variable, because sometimes clarity > cleverness:

# reading from file; more temps
while ( <> ) {
    next unless s/^(.*?):\s*//;
    my $who = $1;
    my $rec = {};
    $HoH{$who} = $rec;
    for my $field ( split ) {
        my ($key, $value) = split /=/, $field;
        $rec->{$key} = $value;
    }
}

Calling a function that hands you back a key,value hash:

# calling a function that returns a key,value hash
for my $group ( "simpsons", "jetsons", "flintstones" ) {
    $HoH{$group} = { get_family($group) };
}

Literally the same, but with a temp, because we respect readability in this house:

# likewise, but using temps
for my $group ( "simpsons", "jetsons", "flintstones" ) {
    my %members = get_family($group);
    $HoH{$group} = { %members };
}

Appending new members to a family that already exists:

# append new members to an existing family
my %new_folks = (
    wife => "wilma",
    pet  => "dino",
);

for my $what (keys %new_folks) {
    $HoH{flintstones}{$what} = $new_folks{$what};
}

Same energy, but with a hash slice, because we're fancy:

# same, but using a hash slice
@{ $HoH{flintstones} }{ keys %new_folks } = values %new_folks;

And same again, but no %new_folks variable at all, we're just raw-dogging it:

# same, but without a %new_folks variable
@{ $HoH{flintstones} }{ "wife", "pet" } = ( "wilma", "dino" );

πŸ¦‹ Access and Printing of a HASH OF HASHES πŸ¦‹

Grabbing one single element:

# one element
$HoH{flintstones}{wife} = "wilma";

Another element, and this time we're capitalizing the first letter because main character energy:

# another element
$HoH{simpsons}{lead} =~ s/(\w)/\u$1/;

Printing the WHOLE thing:

# print the whole thing
foreach my $family ( keys %HoH ) {
    print "$family: { ";
    for my $role ( keys $HoH{$family}->%* ) {
        print "$role=$HoH{$family}{$role} ";
    }
    print "}\n";
}

Printing the whole thing, but sorted, because chaos is not a personality trait:

# print the whole thing somewhat sorted
foreach my $family ( sort keys %HoH ) {
    print "$family: { ";
    for my $role ( sort keys $HoH{$family}->%* ) {
        print "$role=$HoH{$family}{$role} ";
    }
    print "}\n";
}

Printing sorted by how many members each family has:

# print the whole thing sorted by number of members
foreach my $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {
    print "$family: { ";
    for my $role ( sort keys $HoH{$family}->%* ) {
        print "$role=$HoH{$family}{$role} ";
    }
    print "}\n";
}

Now we're establishing a rank order for each role, so the roles print in a sensible order instead of alphabetical chaos:

# establish a sort order (rank) for each role
my $i = 0;
my %rank;
for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }

And here's the whole thing, sorted by member count AND with roles in rank order:

# now print the whole thing sorted by number of members
foreach my $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {
    print "$family: { ";
    # and print these according to rank order
    for my $role ( sort { $rank{$a} <=> $rank{$b} }
                                              keys $HoH{$family}->%* )
    {
        print "$role=$HoH{$family}{$role} ";
    }
    print "}\n";
}

Slay. Look at that nested sort. She ate. πŸ”₯


πŸ‘‘ MORE ELABORATE RECORDS πŸ‘‘

πŸ’œ Declaration of MORE ELABORATE RECORDS πŸ’œ

So a hash of hashes is cute, but what if your record needs fields of many different kinds? Text, arrays, hashes, code refs, filehandles... a whole little ecosystem. Here's a sample showing how to create and use exactly that:

my $rec = {
    TEXT      => $string,
    SEQUENCE  => [ @old_values ],
    LOOKUP    => { %some_table },
    THATCODE  => \&some_function,
    THISCODE  => sub { $_[0] ** $_[1] },
    HANDLE    => \*STDOUT,
};

print $rec->{TEXT};

print $rec->{SEQUENCE}[0];
my $last = pop $rec->{SEQUENCE}->@*;

print $rec->{LOOKUP}{"key"};
my ($first_k, $first_v) = each $rec->{LOOKUP}->%*;

my $answer = $rec->{THATCODE}->($arg);
$answer = $rec->{THISCODE}->($arg1, $arg2);

# careful of extra block braces on fh ref
print { $rec->{HANDLE} } "a string\n";

use FileHandle;
$rec->{HANDLE}->autoflush(1);
$rec->{HANDLE}->print(" a string\n");
Bestie, note the extra block braces on that filehandle print. print { $rec->{HANDLE} } β€” those braces are not decorative, they're load-bearing. Do not remove them, do not "clean them up", the parser will simply not understand you and you will deserve it. πŸ’€

🌈 Declaration of a HASH OF COMPLEX RECORDS 🌈

Now we take those elaborate records and stack them inside a hash keyed by show. Iconic behavior:

my %TV = (
   flintstones => {
       series   => "flintstones",
       nights   => [ qw(monday thursday friday) ],
       members  => [
           { name => "fred",    role => "lead", age  => 36, },
           { name => "wilma",   role => "wife", age  => 31, },
           { name => "pebbles", role => "kid",  age  =>  4, },
       ],
   },

   jetsons     => {
       series   => "jetsons",
       nights   => [ qw(wednesday saturday) ],
       members  => [
           { name => "george",  role => "lead", age  => 41, },
           { name => "jane",    role => "wife", age  => 39, },
           { name => "elroy",   role => "kid",  age  =>  9, },
       ],
    },

   simpsons    => {
       series   => "simpsons",
       nights   => [ qw(monday) ],
       members  => [
           { name => "homer", role => "lead", age  => 34, },
           { name => "marge", role => "wife", age => 37, },
           { name => "bart",  role => "kid",  age  =>  11, },
       ],
    },
 );

Hash of hashes of arrays of hashes. Say that five times fast. It's giving inception, it's giving dream-within-a-dream. 🧚


⭐ Generation of a HASH OF COMPLEX RECORDS ⭐

Reading from a file β€” and honestly the easiest way to do this is just to make the file itself be in that raw data format shown above. Perl is genuinely happy to parse complex data structures if they're declared as data, so sometimes it's easiest to just do that:

# reading from file
# this is most easily done by having the file itself be
# in the raw data format as shown above.  perl is happy
# to parse complex data structures if declared as data, so
# sometimes it's easiest to do that

Here's a piece-by-piece build up:

# here's a piece by piece build up
my $rec = {};
$rec->{series} = "flintstones";
$rec->{nights} = [ find_days() ];

my @members = ();
# assume this file in field=value syntax
while (<>) {
    my %fields = split /[\s=]+/;
    push @members, { %fields };
}
$rec->{members} = [ @members ];

# now remember the whole thing
$TV{ $rec->{series} } = $rec;

And now the spicy part. You might want to make interesting extra fields that include pointers back into the same data structure, so if you change one piece, it changes everywhere. Like, for example, if you wanted a {kids} field that was a reference to an array of the kids' records β€” without having duplicate records and therefore update problems:

###########################################################
# now, you might want to make interesting extra fields that
# include pointers back into the same data structure so if
# change one piece, it changes everywhere, like for example
# if you wanted a {kids} field that was a reference
# to an array of the kids' records without having duplicate
# records and thus update problems.
###########################################################
foreach my $family (keys %TV) {
    my $rec = $TV{$family}; # temp pointer
    my @kids = ();
    for my $person ( $rec->{members}->@* ) {
        if ($person->{role} =~ /kid|son|daughter/) {
            push @kids, $person;
        }
    }
    # REMEMBER: $rec and $TV{$family} point to same data!!
    $rec->{kids} = [ @kids ];
}
REMEMBER: $rec and $TV{$family} point to the same data!! This is not a copy. This is two names for one thing. πŸ’…

Now here's the consequence, and it is important, so read it carefully:

You copied the array, but the array itself contains pointers to uncopied objects. This means that if you make bart get older via

$TV{simpsons}{kids}[0]{age}++;

then this would also change in

print $TV{simpsons}{members}[2]{age};

because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2] both point to the same underlying anonymous hash table.

Not a bug, bestie. A feature. One truth, many doors. πŸšͺ✨

Printing the whole thing:

# print the whole thing
foreach my $family ( keys %TV ) {
    print "the $family";
    print " is on during $TV{$family}{nights}->@*\n";
    print "its members are:\n";
    for my $who ( $TV{$family}{members}->@* ) {
        print " $who->{name} ($who->{role}), age $who->{age}\n";
    }
    print "it turns out that $TV{$family}{lead} has ";
    print scalar ( $TV{$family}{kids}->@* ), " kids named ";
    print join (", ", map { $_->{name} } $TV{$family}{kids}->@* );
    print "\n";
}

πŸŽ€ Database Ties πŸŽ€

Okay so, real talk. You cannot easily tie a multilevel data structure (like, say, a hash of hashes) to a dbm file. Nope. Not happening.

The first problem is that all but GDBM and Berkeley DB have size limitations. But beyond that? You also have problems with how references are to be represented on disk. References on disk is a whole situation.

One experimental module that does partially attempt to address this need is the MLDBM module. Check your nearest CPAN site, as described in perlmodlib, for source code to MLDBM.

So like... it's possible-ish. Partially. Experimentally. Good luck, babe. πŸ™ˆ


🌸 SEE ALSO 🌸

  • perlref
  • perllol
  • perldata
  • perlobj

πŸ’– AUTHOR πŸ’–

Tom Christiansen <tchrist@perl.com>


And that's a wrap on the whole PERLDSC saga, bestie!! πŸŽ‰ This final chunk shipped as part of perl v5.42.3, dated 2026-08-03 β€” so yes, go build your hashes of hashes of arrays of hashes, the documentation has your back. Go forth and nest responsibly. πŸ¦‹πŸ’…

πŸ“¦ where this page comes from