{
    "content": [
        {
            "type": "text",
            "text": "# PERLDSC (man)\n\n## NAME\n\nperldsc - Perl Data Structures Cookbook\n\n## DESCRIPTION\n\nPerl lets us have complex data structures.  You can write something like this and all of a\nsudden, you'd have an array with three dimensions!\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **REFERENCES**\n- **COMMON MISTAKES**\n- **CAVEAT ON PRECEDENCE** (1 subsections)\n- **DEBUGGING**\n- **CODE EXAMPLES**\n- **ARRAYS OF ARRAYS** (3 subsections)\n- **HASHES OF ARRAYS** (3 subsections)\n- **ARRAYS OF HASHES** (3 subsections)\n- **HASHES OF HASHES** (3 subsections)\n- **MORE ELABORATE RECORDS** (4 subsections)\n- **SEE ALSO**\n- **AUTHOR**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "PERLDSC",
        "section": "",
        "mode": "man",
        "summary": "perldsc - Perl Data Structures Cookbook",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 44,
                "subsections": []
            },
            {
                "name": "REFERENCES",
                "lines": 38,
                "subsections": []
            },
            {
                "name": "COMMON MISTAKES",
                "lines": 133,
                "subsections": []
            },
            {
                "name": "CAVEAT ON PRECEDENCE",
                "lines": 17,
                "subsections": [
                    {
                        "name": "WHY YOU SHOULD ALWAYS \"use strict\"",
                        "lines": 23
                    }
                ]
            },
            {
                "name": "DEBUGGING",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "CODE EXAMPLES",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "ARRAYS OF ARRAYS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Declaration of an ARRAY OF ARRAYS",
                        "lines": 6
                    },
                    {
                        "name": "Generation of an ARRAY OF ARRAYS",
                        "lines": 19
                    },
                    {
                        "name": "Access and Printing of an ARRAY OF ARRAYS",
                        "lines": 23
                    }
                ]
            },
            {
                "name": "HASHES OF ARRAYS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Declaration of a HASH OF ARRAYS",
                        "lines": 6
                    },
                    {
                        "name": "Generation of a HASH OF ARRAYS",
                        "lines": 29
                    },
                    {
                        "name": "Access and Printing of a HASH OF ARRAYS",
                        "lines": 35
                    }
                ]
            },
            {
                "name": "ARRAYS OF HASHES",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Declaration of an ARRAY OF HASHES",
                        "lines": 17
                    },
                    {
                        "name": "Generation of an ARRAY OF HASHES",
                        "lines": 34
                    },
                    {
                        "name": "Access and Printing of an ARRAY OF HASHES",
                        "lines": 31
                    }
                ]
            },
            {
                "name": "HASHES OF HASHES",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Declaration of a HASH OF HASHES",
                        "lines": 17
                    },
                    {
                        "name": "Generation of a HASH OF HASHES",
                        "lines": 44
                    },
                    {
                        "name": "Access and Printing of a HASH OF HASHES",
                        "lines": 50
                    }
                ]
            },
            {
                "name": "MORE ELABORATE RECORDS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Declaration of MORE ELABORATE RECORDS",
                        "lines": 30
                    },
                    {
                        "name": "Declaration of a HASH OF COMPLEX RECORDS",
                        "lines": 32
                    },
                    {
                        "name": "Generation of a HASH OF COMPLEX RECORDS",
                        "lines": 68
                    },
                    {
                        "name": "Database Ties",
                        "lines": 6
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "perldsc - Perl Data Structures Cookbook\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "Perl lets us have complex data structures.  You can write something like this and all of a\nsudden, you'd have an array with three dimensions!\n\nfor my $x (1 .. 10) {\nfor my $y (1 .. 10) {\nfor my $z (1 .. 10) {\n$AoA[$x][$y][$z] =\n$x  $y + $z;\n}\n}\n}\n\nAlas, however simple this may appear, underneath it's a much more elaborate construct than\nmeets the eye!\n\nHow do you print it out?  Why can't you say just \"print @AoA\"?  How do you sort it?  How can\nyou pass it to a function or get one of these back from a function?  Is it an object?  Can\nyou save it to disk to read back later?  How do you access whole rows or columns of that\nmatrix?  Do all the values have to be numeric?\n\nAs you see, it's quite easy to become confused.  While some small portion of the blame for\nthis can be attributed to the reference-based implementation, it's really more due to a lack\nof existing documentation with examples designed for the beginner.\n\nThis document is meant to be a detailed but understandable treatment of the many different\nsorts of data structures you might want to develop.  It should also serve as a cookbook of\nexamples.  That way, when you need to create one of these complex data structures, you can\njust pinch, pilfer, or purloin a drop-in example from here.\n\nLet's look at each of these possible constructs in detail.  There are separate sections on\neach of the following:\n\n•    arrays of arrays\n\n•    hashes of arrays\n\n•    arrays of hashes\n\n•    hashes of hashes\n\n•    more elaborate constructs\n\nBut for now, let's look at general issues common to all these types of data structures.\n",
                "subsections": []
            },
            "REFERENCES": {
                "content": "The most important thing to understand about all data structures in Perl--including\nmultidimensional arrays--is that even though they might appear otherwise, Perl @ARRAYs and\n%HASHes are all internally one-dimensional.  They can hold only scalar values (meaning a\nstring, number, or a reference).  They cannot directly contain other arrays or hashes, but\ninstead contain references to other arrays or hashes.\n\nYou can't use a reference to an array or hash in quite the same way that you would a real\narray or hash.  For C or C++ programmers unused to distinguishing between arrays and pointers\nto the same, this can be confusing.  If so, just think of it as the difference between a\nstructure and a pointer to a structure.\n\nYou can (and should) read more about references in perlref.  Briefly, references are rather\nlike pointers that know what they point to.  (Objects are also a kind of reference, but we\nwon't be needing them right away--if ever.)  This means that when you have something which\nlooks to you like an access to a two-or-more-dimensional array and/or hash, what's really\ngoing on is that the base type is merely a one-dimensional entity that contains references to\nthe next level.  It's just that you can use it as though it were a two-dimensional one.  This\nis actually the way almost all C multidimensional arrays work as well.\n\n$array[7][12]                       # array of arrays\n$array[7]{string}                   # array of hashes\n$hash{string}[7]                    # hash of arrays\n$hash{string}{'another string'}     # hash of hashes\n\nNow, because the top level contains only references, if you try to print out your array in\nwith a simple print() function, you'll get something that doesn't look very nice, like this:\n\nmy @AoA = ( [2, 3], [4, 5, 7], [0] );\nprint $AoA[1][2];\n7\nprint @AoA;\nARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)\n\nThat's because Perl doesn't (ever) implicitly dereference your variables.  If you want to get\nat the thing a reference is referring to, then you have to do this yourself using either\nprefix typing indicators, like \"${$blah}\", \"@{$blah}\", \"@{$blah[$i]}\", or else postfix\npointer arrows, like \"$a->[3]\", \"$h->{fred}\", or even \"$ob->method()->[3]\".\n",
                "subsections": []
            },
            "COMMON MISTAKES": {
                "content": "The two most common mistakes made in constructing something like an array of arrays is either\naccidentally counting the number of elements or else taking a reference to the same memory\nlocation repeatedly.  Here's the case where you just get the count instead of a nested array:\n\nfor my $i (1..10) {\nmy @array = somefunc($i);\n$AoA[$i] = @array;      # WRONG!\n}\n\nThat's just the simple case of assigning an array to a scalar and getting its element count.\nIf that's what you really and truly want, then you might do well to consider being a tad more\nexplicit about it, like this:\n\nfor my $i (1..10) {\nmy @array = somefunc($i);\n$counts[$i] = scalar @array;\n}\n\nHere's the case of taking a reference to the same memory location again and again:\n\n# Either without strict or having an outer-scope my @array;\n# declaration.\n\nfor my $i (1..10) {\n@array = somefunc($i);\n$AoA[$i] = \\@array;     # WRONG!\n}\n\nSo, what's the big problem with that?  It looks right, doesn't it?  After all, I just told\nyou that you need an array of references, so by golly, you've made me one!\n\nUnfortunately, while this is true, it's still broken.  All the references in @AoA refer to\nthe very same place, and they will therefore all hold whatever was last in @array!  It's\nsimilar to the problem demonstrated in the following C program:\n\n#include <pwd.h>\nmain() {\nstruct passwd *getpwnam(), *rp, *dp;\nrp = getpwnam(\"root\");\ndp = getpwnam(\"daemon\");\n\nprintf(\"daemon name is %s\\nroot name is %s\\n\",\ndp->pwname, rp->pwname);\n}\n\nWhich will print\n\ndaemon name is daemon\nroot name is daemon\n\nThe problem is that both \"rp\" and \"dp\" are pointers to the same location in memory!  In C,\nyou'd have to remember to malloc() yourself some new memory.  In Perl, you'll want to use the\narray constructor \"[]\" or the hash constructor \"{}\" instead.   Here's the right way to do the\npreceding broken code fragments:\n\n# Either without strict or having an outer-scope my @array;\n# declaration.\n\nfor my $i (1..10) {\n@array = somefunc($i);\n$AoA[$i] = [ @array ];\n}\n\nThe square brackets make a reference to a new array with a copy of what's in @array at the\ntime of the assignment.  This is what you want.\n\nNote that this will produce something similar:\n\n# Either without strict or having an outer-scope my @array;\n# declaration.\nfor my $i (1..10) {\n@array = 0 .. $i;\n$AoA[$i]->@* = @array;\n}\n\nIs it the same?  Well, maybe so--and maybe not.  The subtle difference is that when you\nassign something in square brackets, you know for sure it's always a brand new reference with\na new copy of the data.  Something else could be going on in this new case with the\n\"$AoA[$i]->@*\" dereference on the left-hand-side of the assignment.  It all depends on\nwhether $AoA[$i] had been undefined to start with, or whether it already contained a\nreference.  If you had already populated @AoA with references, as in\n\n$AoA[3] = \\@anotherarray;\n\nThen the assignment with the indirection on the left-hand-side would use the existing\nreference that was already there:\n\n$AoA[3]->@* = @array;\n\nOf course, this would have the \"interesting\" effect of clobbering @anotherarray.  (Have you\never noticed how when a programmer says something is \"interesting\", that rather than meaning\n\"intriguing\", they're disturbingly more apt to mean that it's \"annoying\", \"difficult\", or\nboth?  :-)\n\nSo just remember always to use the array or hash constructors with \"[]\" or \"{}\", and you'll\nbe fine, although it's not always optimally efficient.\n\nSurprisingly, the following dangerous-looking construct will actually work out fine:\n\nfor my $i (1..10) {\nmy @array = somefunc($i);\n$AoA[$i] = \\@array;\n}\n\nThat's because my() is more of a run-time statement than it is a compile-time declaration per\nse.  This means that the my() variable is remade afresh each time through the loop.  So even\nthough it looks as though you stored the same variable reference each time, you actually did\nnot!  This is a subtle distinction that can produce more efficient code at the risk of\nmisleading all but the most experienced of programmers.  So I usually advise against teaching\nit to beginners.  In fact, except for passing arguments to functions, I seldom like to see\nthe gimme-a-reference operator (backslash) used much at all in code.  Instead, I advise\nbeginners that they (and most of the rest of us) should try to use the much more easily\nunderstood constructors \"[]\" and \"{}\" instead of relying upon lexical (or dynamic) scoping\nand hidden reference-counting to do the right thing behind the scenes.\n\nNote also that there exists another way to write a dereference!  These two lines are\nequivalent:\n\n$AoA[$i]->@* = @array;\n@{ $AoA[$i] } = @array;\n\nThe first form, called postfix dereference is generally easier to read, because the\nexpression can be read from left to right, and there are no enclosing braces to balance.  On\nthe other hand, it is also newer.  It was added to the language in 2014, so you will often\nencounter the other form, circumfix dereference, in older code.\n\nIn summary:\n\n$AoA[$i] = [ @array ];     # usually best\n$AoA[$i] = \\@array;        # perilous; just how my() was that array?\n$AoA[$i]->@*  = @array;    # way too tricky for most programmers\n@{ $AoA[$i] } = @array;    # just as tricky, and also harder to read\n",
                "subsections": []
            },
            "CAVEAT ON PRECEDENCE": {
                "content": "Speaking of things like \"@{$AoA[$i]}\", the following are actually the same thing:\n\n$aref->[2][2]       # clear\n$$aref[2][2]        # confusing\n\nThat's because Perl's precedence rules on its five prefix dereferencers (which look like\nsomeone swearing: \"$ @ * % &\") make them bind more tightly than the postfix subscripting\nbrackets or braces!  This will no doubt come as a great shock to the C or C++ programmer, who\nis quite accustomed to using *a[i] to mean what's pointed to by the i'th element of \"a\".\nThat is, they first take the subscript, and only then dereference the thing at that\nsubscript.  That's fine in C, but this isn't C.\n\nThe seemingly equivalent construct in Perl, $$aref[$i] first does the deref of $aref, making\nit take $aref as a reference to an array, and then dereference that, and finally tell you the\ni'th value of the array pointed to by $AoA. If you wanted the C notion, you could write\n\"$AoA[$i]->$*\" to explicitly dereference the i'th item, reading left to right.\n",
                "subsections": [
                    {
                        "name": "WHY YOU SHOULD ALWAYS \"use strict\"",
                        "content": "If this is starting to sound scarier than it's worth, relax.  Perl has some features to help\nyou avoid its most common pitfalls.  The best way to avoid getting confused is to start every\nprogram with:\n\nuse strict;\n\nThis way, you'll be forced to declare all your variables with my() and also disallow\naccidental \"symbolic dereferencing\".  Therefore if you'd done this:\n\nmy $aref = [\n[ \"fred\", \"barney\", \"pebbles\", \"bambam\", \"dino\", ],\n[ \"homer\", \"bart\", \"marge\", \"maggie\", ],\n[ \"george\", \"jane\", \"elroy\", \"judy\", ],\n];\n\nprint $aref[2][2];\n\nThe compiler would immediately flag that as an error at compile time, because you were\naccidentally accessing @aref, an undeclared variable, and it would thereby remind you to\nwrite instead:\n\nprint $aref->[2][2]\n"
                    }
                ]
            },
            "DEBUGGING": {
                "content": "You can use the debugger's \"x\" command to dump out complex data structures.  For example,\ngiven the assignment to $AoA above, here's the debugger output:\n\nDB<1> x $AoA\n$AoA = ARRAY(0x13b5a0)\n0  ARRAY(0x1f0a24)\n0  'fred'\n1  'barney'\n2  'pebbles'\n3  'bambam'\n4  'dino'\n1  ARRAY(0x13b558)\n0  'homer'\n1  'bart'\n2  'marge'\n3  'maggie'\n2  ARRAY(0x13b540)\n0  'george'\n1  'jane'\n2  'elroy'\n3  'judy'\n",
                "subsections": []
            },
            "CODE EXAMPLES": {
                "content": "Presented with little comment here are short code examples illustrating access of various\ntypes of data structures.\n",
                "subsections": []
            },
            "ARRAYS OF ARRAYS": {
                "content": "",
                "subsections": [
                    {
                        "name": "Declaration of an ARRAY OF ARRAYS",
                        "content": "@AoA = (\n[ \"fred\", \"barney\" ],\n[ \"george\", \"jane\", \"elroy\" ],\n[ \"homer\", \"marge\", \"bart\" ],\n);\n"
                    },
                    {
                        "name": "Generation of an ARRAY OF ARRAYS",
                        "content": "# reading from file\nwhile ( <> ) {\npush @AoA, [ split ];\n}\n\n# calling a function\nfor $i ( 1 .. 10 ) {\n$AoA[$i] = [ somefunc($i) ];\n}\n\n# using temp vars\nfor $i ( 1 .. 10 ) {\n@tmp = somefunc($i);\n$AoA[$i] = [ @tmp ];\n}\n\n# add to an existing row\npush $AoA[0]->@*, \"wilma\", \"betty\";\n"
                    },
                    {
                        "name": "Access and Printing of an ARRAY OF ARRAYS",
                        "content": "# one element\n$AoA[0][0] = \"Fred\";\n\n# another element\n$AoA[1][1] =~ s/(\\w)/\\u$1/;\n\n# print the whole thing with refs\nfor $aref ( @AoA ) {\nprint \"\\t [ @$aref ],\\n\";\n}\n\n# print the whole thing with indices\nfor $i ( 0 .. $#AoA ) {\nprint \"\\t [ $AoA[$i]->@* ],\\n\";\n}\n\n# print the whole thing one at a time\nfor $i ( 0 .. $#AoA ) {\nfor $j ( 0 .. $AoA[$i]->$#* ) {\nprint \"elem at ($i, $j) is $AoA[$i][$j]\\n\";\n}\n}\n"
                    }
                ]
            },
            "HASHES OF ARRAYS": {
                "content": "",
                "subsections": [
                    {
                        "name": "Declaration of a HASH OF ARRAYS",
                        "content": "%HoA = (\nflintstones        => [ \"fred\", \"barney\" ],\njetsons            => [ \"george\", \"jane\", \"elroy\" ],\nsimpsons           => [ \"homer\", \"marge\", \"bart\" ],\n);\n"
                    },
                    {
                        "name": "Generation of a HASH OF ARRAYS",
                        "content": "# reading from file\n# flintstones: fred barney wilma dino\nwhile ( <> ) {\nnext unless s/^(.*?):\\s*//;\n$HoA{$1} = [ split ];\n}\n\n# reading from file; more temps\n# flintstones: fred barney wilma dino\nwhile ( $line = <> ) {\n($who, $rest) = split /:\\s*/, $line, 2;\n@fields = split ' ', $rest;\n$HoA{$who} = [ @fields ];\n}\n\n# calling a function that returns a list\nfor $group ( \"simpsons\", \"jetsons\", \"flintstones\" ) {\n$HoA{$group} = [ getfamily($group) ];\n}\n\n# likewise, but using temps\nfor $group ( \"simpsons\", \"jetsons\", \"flintstones\" ) {\n@members = getfamily($group);\n$HoA{$group} = [ @members ];\n}\n\n# append new members to an existing family\npush $HoA{flintstones}->@*, \"wilma\", \"betty\";\n"
                    },
                    {
                        "name": "Access and Printing of a HASH OF ARRAYS",
                        "content": "# one element\n$HoA{flintstones}[0] = \"Fred\";\n\n# another element\n$HoA{simpsons}[1] =~ s/(\\w)/\\u$1/;\n\n# print the whole thing\nforeach $family ( keys %HoA ) {\nprint \"$family: $HoA{$family}->@* \\n\"\n}\n\n# print the whole thing with indices\nforeach $family ( keys %HoA ) {\nprint \"family: \";\nforeach $i ( 0 .. $HoA{$family}->$#* ) {\nprint \" $i = $HoA{$family}[$i]\";\n}\nprint \"\\n\";\n}\n\n# print the whole thing sorted by number of members\nforeach $family ( sort { $HoA{$b}->@* <=> $HoA{$a}->@* } keys %HoA ) {\nprint \"$family: $HoA{$family}->@* \\n\"\n}\n\n# print the whole thing sorted by number of members and name\nforeach $family ( sort {\n$HoA{$b}->@* <=> $HoA{$a}->@*\n||\n$a cmp $b\n} keys %HoA )\n{\nprint \"$family: \", join(\", \", sort $HoA{$family}->@* ), \"\\n\";\n}\n"
                    }
                ]
            },
            "ARRAYS OF HASHES": {
                "content": "",
                "subsections": [
                    {
                        "name": "Declaration of an ARRAY OF HASHES",
                        "content": "@AoH = (\n{\nLead     => \"fred\",\nFriend   => \"barney\",\n},\n{\nLead     => \"george\",\nWife     => \"jane\",\nSon      => \"elroy\",\n},\n{\nLead     => \"homer\",\nWife     => \"marge\",\nSon      => \"bart\",\n}\n);\n"
                    },
                    {
                        "name": "Generation of an ARRAY OF HASHES",
                        "content": "# reading from file\n# format: LEAD=fred FRIEND=barney\nwhile ( <> ) {\n$rec = {};\nfor $field ( split ) {\n($key, $value) = split /=/, $field;\n$rec->{$key} = $value;\n}\npush @AoH, $rec;\n}\n\n\n# reading from file\n# format: LEAD=fred FRIEND=barney\n# no temp\nwhile ( <> ) {\npush @AoH, { split /[\\s+=]/ };\n}\n\n# calling a function  that returns a key/value pair list, like\n# \"lead\",\"fred\",\"daughter\",\"pebbles\"\nwhile ( %fields = getnextpairset() ) {\npush @AoH, { %fields };\n}\n\n# likewise, but using no temp vars\nwhile (<>) {\npush @AoH, { parsepairs($) };\n}\n\n# add key/value to an element\n$AoH[0]{pet} = \"dino\";\n$AoH[2]{pet} = \"santa's little helper\";\n"
                    },
                    {
                        "name": "Access and Printing of an ARRAY OF HASHES",
                        "content": "# one element\n$AoH[0]{lead} = \"fred\";\n\n# another element\n$AoH[1]{lead} =~ s/(\\w)/\\u$1/;\n\n# print the whole thing with refs\nfor $href ( @AoH ) {\nprint \"{ \";\nfor $role ( keys %$href ) {\nprint \"$role=$href->{$role} \";\n}\nprint \"}\\n\";\n}\n\n# print the whole thing with indices\nfor $i ( 0 .. $#AoH ) {\nprint \"$i is { \";\nfor $role ( keys $AoH[$i]->%* ) {\nprint \"$role=$AoH[$i]{$role} \";\n}\nprint \"}\\n\";\n}\n\n# print the whole thing one at a time\nfor $i ( 0 .. $#AoH ) {\nfor $role ( keys $AoH[$i]->%* ) {\nprint \"elem at ($i, $role) is $AoH[$i]{$role}\\n\";\n}\n}\n"
                    }
                ]
            },
            "HASHES OF HASHES": {
                "content": "",
                "subsections": [
                    {
                        "name": "Declaration of a HASH OF HASHES",
                        "content": "%HoH = (\nflintstones => {\nlead      => \"fred\",\npal       => \"barney\",\n},\njetsons     => {\nlead      => \"george\",\nwife      => \"jane\",\n\"his boy\" => \"elroy\",\n},\nsimpsons    => {\nlead      => \"homer\",\nwife      => \"marge\",\nkid       => \"bart\",\n},\n);\n"
                    },
                    {
                        "name": "Generation of a HASH OF HASHES",
                        "content": "# reading from file\n# flintstones: lead=fred pal=barney wife=wilma pet=dino\nwhile ( <> ) {\nnext unless s/^(.*?):\\s*//;\n$who = $1;\nfor $field ( split ) {\n($key, $value) = split /=/, $field;\n$HoH{$who}{$key} = $value;\n}\n\n\n# reading from file; more temps\nwhile ( <> ) {\nnext unless s/^(.*?):\\s*//;\n$who = $1;\n$rec = {};\n$HoH{$who} = $rec;\nfor $field ( split ) {\n($key, $value) = split /=/, $field;\n$rec->{$key} = $value;\n}\n}\n\n# calling a function  that returns a key,value hash\nfor $group ( \"simpsons\", \"jetsons\", \"flintstones\" ) {\n$HoH{$group} = { getfamily($group) };\n}\n\n# likewise, but using temps\nfor $group ( \"simpsons\", \"jetsons\", \"flintstones\" ) {\n%members = getfamily($group);\n$HoH{$group} = { %members };\n}\n\n# append new members to an existing family\n%newfolks = (\nwife => \"wilma\",\npet  => \"dino\",\n);\n\nfor $what (keys %newfolks) {\n$HoH{flintstones}{$what} = $newfolks{$what};\n}\n"
                    },
                    {
                        "name": "Access and Printing of a HASH OF HASHES",
                        "content": "# one element\n$HoH{flintstones}{wife} = \"wilma\";\n\n# another element\n$HoH{simpsons}{lead} =~ s/(\\w)/\\u$1/;\n\n# print the whole thing\nforeach $family ( keys %HoH ) {\nprint \"$family: { \";\nfor $role ( keys $HoH{$family}->%* ) {\nprint \"$role=$HoH{$family}{$role} \";\n}\nprint \"}\\n\";\n}\n\n# print the whole thing  somewhat sorted\nforeach $family ( sort keys %HoH ) {\nprint \"$family: { \";\nfor $role ( sort keys $HoH{$family}->%* ) {\nprint \"$role=$HoH{$family}{$role} \";\n}\nprint \"}\\n\";\n}\n\n\n# print the whole thing sorted by number of members\nforeach $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {\nprint \"$family: { \";\nfor $role ( sort keys $HoH{$family}->%* ) {\nprint \"$role=$HoH{$family}{$role} \";\n}\nprint \"}\\n\";\n}\n\n# establish a sort order (rank) for each role\n$i = 0;\nfor ( qw(lead wife son daughter pal pet) ) { $rank{$} = ++$i }\n\n# now print the whole thing sorted by number of members\nforeach $family ( sort { $HoH{$b}->%* <=> $HoH{$a}->%* } keys %HoH ) {\nprint \"$family: { \";\n# and print these according to rank order\nfor $role ( sort { $rank{$a} <=> $rank{$b} }\nkeys $HoH{$family}->%* )\n{\nprint \"$role=$HoH{$family}{$role} \";\n}\nprint \"}\\n\";\n}\n"
                    }
                ]
            },
            "MORE ELABORATE RECORDS": {
                "content": "",
                "subsections": [
                    {
                        "name": "Declaration of MORE ELABORATE RECORDS",
                        "content": "Here's a sample showing how to create and use a record whose fields are of many different\nsorts:\n\n$rec = {\nTEXT      => $string,\nSEQUENCE  => [ @oldvalues ],\nLOOKUP    => { %sometable },\nTHATCODE  => \\&somefunction,\nTHISCODE  => sub { $[0]  $[1] },\nHANDLE    => \\*STDOUT,\n};\n\nprint $rec->{TEXT};\n\nprint $rec->{SEQUENCE}[0];\n$last = pop $rec->{SEQUENCE}->@*;\n\nprint $rec->{LOOKUP}{\"key\"};\n($firstk, $firstv) = each $rec->{LOOKUP}->%*;\n\n$answer = $rec->{THATCODE}->($arg);\n$answer = $rec->{THISCODE}->($arg1, $arg2);\n\n# careful of extra block braces on fh ref\nprint { $rec->{HANDLE} } \"a string\\n\";\n\nuse FileHandle;\n$rec->{HANDLE}->autoflush(1);\n$rec->{HANDLE}->print(\" a string\\n\");\n"
                    },
                    {
                        "name": "Declaration of a HASH OF COMPLEX RECORDS",
                        "content": "%TV = (\nflintstones => {\nseries   => \"flintstones\",\nnights   => [ qw(monday thursday friday) ],\nmembers  => [\n{ name => \"fred\",    role => \"lead\", age  => 36, },\n{ name => \"wilma\",   role => \"wife\", age  => 31, },\n{ name => \"pebbles\", role => \"kid\",  age  =>  4, },\n],\n},\n\njetsons     => {\nseries   => \"jetsons\",\nnights   => [ qw(wednesday saturday) ],\nmembers  => [\n{ name => \"george\",  role => \"lead\", age  => 41, },\n{ name => \"jane\",    role => \"wife\", age  => 39, },\n{ name => \"elroy\",   role => \"kid\",  age  =>  9, },\n],\n},\n\nsimpsons    => {\nseries   => \"simpsons\",\nnights   => [ qw(monday) ],\nmembers  => [\n{ name => \"homer\", role => \"lead\", age  => 34, },\n{ name => \"marge\", role => \"wife\", age => 37, },\n{ name => \"bart\",  role => \"kid\",  age  =>  11, },\n],\n},\n);\n"
                    },
                    {
                        "name": "Generation of a HASH OF COMPLEX RECORDS",
                        "content": "# reading from file\n# this is most easily done by having the file itself be\n# in the raw data format as shown above.  perl is happy\n# to parse complex data structures if declared as data, so\n# sometimes it's easiest to do that\n\n# here's a piece by piece build up\n$rec = {};\n$rec->{series} = \"flintstones\";\n$rec->{nights} = [ finddays() ];\n\n@members = ();\n# assume this file in field=value syntax\nwhile (<>) {\n%fields = split /[\\s=]+/;\npush @members, { %fields };\n}\n$rec->{members} = [ @members ];\n\n# now remember the whole thing\n$TV{ $rec->{series} } = $rec;\n\n###########################################################\n# now, you might want to make interesting extra fields that\n# include pointers back into the same data structure so if\n# change one piece, it changes everywhere, like for example\n# if you wanted a {kids} field that was a reference\n# to an array of the kids' records without having duplicate\n# records and thus update problems.\n###########################################################\nforeach $family (keys %TV) {\n$rec = $TV{$family}; # temp pointer\n@kids = ();\nfor $person ( $rec->{members}->@* ) {\nif ($person->{role} =~ /kid|son|daughter/) {\npush @kids, $person;\n}\n}\n# REMEMBER: $rec and $TV{$family} point to same data!!\n$rec->{kids} = [ @kids ];\n}\n\n# you copied the array, but the array itself contains pointers\n# to uncopied objects. this means that if you make bart get\n# older via\n\n$TV{simpsons}{kids}[0]{age}++;\n\n# then this would also change in\nprint $TV{simpsons}{members}[2]{age};\n\n# because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]\n# both point to the same underlying anonymous hash table\n\n# print the whole thing\nforeach $family ( keys %TV ) {\nprint \"the $family\";\nprint \" is on during $TV{$family}{nights}->@*\\n\";\nprint \"its members are:\\n\";\nfor $who ( $TV{$family}{members}->@* ) {\nprint \" $who->{name} ($who->{role}), age $who->{age}\\n\";\n}\nprint \"it turns out that $TV{$family}{lead} has \";\nprint scalar ( $TV{$family}{kids}->@* ), \" kids named \";\nprint join (\", \", map { $->{name} } $TV{$family}{kids}->@* );\nprint \"\\n\";\n}\n"
                    },
                    {
                        "name": "Database Ties",
                        "content": "You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file.\nThe first problem is that all but GDBM and Berkeley DB have size limitations, but beyond\nthat, you also have problems with how references are to be represented on disk.  One\nexperimental module that does partially attempt to address this need is the MLDBM module.\nCheck your nearest CPAN site as described in perlmodlib for source code to MLDBM.\n"
                    }
                ]
            },
            "SEE ALSO": {
                "content": "perlref, perllol, perldata, perlobj\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Tom Christiansen <tchrist@perl.com>\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLDSC(1)",
                "subsections": []
            }
        }
    }
}