1PERLDSC(1)             Perl Programmers Reference Guide             PERLDSC(1)
2
3
4

NAME

6       perldsc - Perl Data Structures Cookbook
7

DESCRIPTION

9       The single feature most sorely lacking in the Perl programming language
10       prior to its 5.0 release was complex data structures.  Even without
11       direct language support, some valiant programmers did manage to emulate
12       them, but it was hard work and not for the faint of heart.  You could
13       occasionally get away with the $m{$AoA,$b} notation borrowed from awk
14       in which the keys are actually more like a single concatenated string
15       "$AoA$b", but traversal and sorting were difficult.  More desperate
16       programmers even hacked Perl's internal symbol table directly, a
17       strategy that proved hard to develop and maintain--to put it mildly.
18
19       The 5.0 release of Perl let us have complex data structures.  You may
20       now write something like this and all of a sudden, you'd have an array
21       with three dimensions!
22
23           for $x (1 .. 10) {
24               for $y (1 .. 10) {
25                   for $z (1 .. 10) {
26                       $AoA[$x][$y][$z] =
27                           $x ** $y + $z;
28                   }
29               }
30           }
31
32       Alas, however simple this may appear, underneath it's a much more
33       elaborate construct than meets the eye!
34
35       How do you print it out?  Why can't you say just "print @AoA"?  How do
36       you sort it?  How can you pass it to a function or get one of these
37       back from a function?  Is it an object?  Can you save it to disk to
38       read back later?  How do you access whole rows or columns of that
39       matrix?  Do all the values have to be numeric?
40
41       As you see, it's quite easy to become confused.  While some small
42       portion of the blame for this can be attributed to the reference-based
43       implementation, it's really more due to a lack of existing
44       documentation with examples designed for the beginner.
45
46       This document is meant to be a detailed but understandable treatment of
47       the many different sorts of data structures you might want to develop.
48       It should also serve as a cookbook of examples.  That way, when you
49       need to create one of these complex data structures, you can just
50       pinch, pilfer, or purloin a drop-in example from here.
51
52       Let's look at each of these possible constructs in detail.  There are
53       separate sections on each of the following:
54
55       ·    arrays of arrays
56
57       ·    hashes of arrays
58
59       ·    arrays of hashes
60
61       ·    hashes of hashes
62
63       ·    more elaborate constructs
64
65       But for now, let's look at general issues common to all these types of
66       data structures.
67

REFERENCES

69       The most important thing to understand about all data structures in
70       Perl--including multidimensional arrays--is that even though they might
71       appear otherwise, Perl @ARRAYs and %HASHes are all internally one-
72       dimensional.  They can hold only scalar values (meaning a string,
73       number, or a reference).  They cannot directly contain other arrays or
74       hashes, but instead contain references to other arrays or hashes.
75
76       You can't use a reference to an array or hash in quite the same way
77       that you would a real array or hash.  For C or C++ programmers unused
78       to distinguishing between arrays and pointers to the same, this can be
79       confusing.  If so, just think of it as the difference between a
80       structure and a pointer to a structure.
81
82       You can (and should) read more about references in the perlref(1) man
83       page.  Briefly, references are rather like pointers that know what they
84       point to.  (Objects are also a kind of reference, but we won't be
85       needing them right away--if ever.)  This means that when you have
86       something which looks to you like an access to a two-or-more-
87       dimensional array and/or hash, what's really going on is that the base
88       type is merely a one-dimensional entity that contains references to the
89       next level.  It's just that you can use it as though it were a two-
90       dimensional one.  This is actually the way almost all C
91       multidimensional arrays work as well.
92
93           $array[7][12]                       # array of arrays
94           $array[7]{string}                   # array of hashes
95           $hash{string}[7]                    # hash of arrays
96           $hash{string}{'another string'}     # hash of hashes
97
98       Now, because the top level contains only references, if you try to
99       print out your array in with a simple print() function, you'll get
100       something that doesn't look very nice, like this:
101
102           @AoA = ( [2, 3], [4, 5, 7], [0] );
103           print $AoA[1][2];
104         7
105           print @AoA;
106         ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
107
108       That's because Perl doesn't (ever) implicitly dereference your
109       variables.  If you want to get at the thing a reference is referring
110       to, then you have to do this yourself using either prefix typing
111       indicators, like "${$blah}", "@{$blah}", "@{$blah[$i]}", or else
112       postfix pointer arrows, like "$a->[3]", "$h->{fred}", or even
113       "$ob->method()->[3]".
114

COMMON MISTAKES

116       The two most common mistakes made in constructing something like an
117       array of arrays is either accidentally counting the number of elements
118       or else taking a reference to the same memory location repeatedly.
119       Here's the case where you just get the count instead of a nested array:
120
121           for $i (1..10) {
122               @array = somefunc($i);
123               $AoA[$i] = @array;      # WRONG!
124           }
125
126       That's just the simple case of assigning an array to a scalar and
127       getting its element count.  If that's what you really and truly want,
128       then you might do well to consider being a tad more explicit about it,
129       like this:
130
131           for $i (1..10) {
132               @array = somefunc($i);
133               $counts[$i] = scalar @array;
134           }
135
136       Here's the case of taking a reference to the same memory location again
137       and again:
138
139           for $i (1..10) {
140               @array = somefunc($i);
141               $AoA[$i] = \@array;     # WRONG!
142           }
143
144       So, what's the big problem with that?  It looks right, doesn't it?
145       After all, I just told you that you need an array of references, so by
146       golly, you've made me one!
147
148       Unfortunately, while this is true, it's still broken.  All the
149       references in @AoA refer to the very same place, and they will
150       therefore all hold whatever was last in @array!  It's similar to the
151       problem demonstrated in the following C program:
152
153           #include <pwd.h>
154           main() {
155               struct passwd *getpwnam(), *rp, *dp;
156               rp = getpwnam("root");
157               dp = getpwnam("daemon");
158
159               printf("daemon name is %s\nroot name is %s\n",
160                       dp->pw_name, rp->pw_name);
161           }
162
163       Which will print
164
165           daemon name is daemon
166           root name is daemon
167
168       The problem is that both "rp" and "dp" are pointers to the same
169       location in memory!  In C, you'd have to remember to malloc() yourself
170       some new memory.  In Perl, you'll want to use the array constructor
171       "[]" or the hash constructor "{}" instead.   Here's the right way to do
172       the preceding broken code fragments:
173
174           for $i (1..10) {
175               @array = somefunc($i);
176               $AoA[$i] = [ @array ];
177           }
178
179       The square brackets make a reference to a new array with a copy of
180       what's in @array at the time of the assignment.  This is what you want.
181
182       Note that this will produce something similar, but it's much harder to
183       read:
184
185           for $i (1..10) {
186               @array = 0 .. $i;
187               @{$AoA[$i]} = @array;
188           }
189
190       Is it the same?  Well, maybe so--and maybe not.  The subtle difference
191       is that when you assign something in square brackets, you know for sure
192       it's always a brand new reference with a new copy of the data.
193       Something else could be going on in this new case with the
194       "@{$AoA[$i]}" dereference on the left-hand-side of the assignment.  It
195       all depends on whether $AoA[$i] had been undefined to start with, or
196       whether it already contained a reference.  If you had already populated
197       @AoA with references, as in
198
199           $AoA[3] = \@another_array;
200
201       Then the assignment with the indirection on the left-hand-side would
202       use the existing reference that was already there:
203
204           @{$AoA[3]} = @array;
205
206       Of course, this would have the "interesting" effect of clobbering
207       @another_array.  (Have you ever noticed how when a programmer says
208       something is "interesting", that rather than meaning "intriguing",
209       they're disturbingly more apt to mean that it's "annoying",
210       "difficult", or both?  :-)
211
212       So just remember always to use the array or hash constructors with "[]"
213       or "{}", and you'll be fine, although it's not always optimally
214       efficient.
215
216       Surprisingly, the following dangerous-looking construct will actually
217       work out fine:
218
219           for $i (1..10) {
220               my @array = somefunc($i);
221               $AoA[$i] = \@array;
222           }
223
224       That's because my() is more of a run-time statement than it is a
225       compile-time declaration per se.  This means that the my() variable is
226       remade afresh each time through the loop.  So even though it looks as
227       though you stored the same variable reference each time, you actually
228       did not!  This is a subtle distinction that can produce more efficient
229       code at the risk of misleading all but the most experienced of
230       programmers.  So I usually advise against teaching it to beginners.  In
231       fact, except for passing arguments to functions, I seldom like to see
232       the gimme-a-reference operator (backslash) used much at all in code.
233       Instead, I advise beginners that they (and most of the rest of us)
234       should try to use the much more easily understood constructors "[]" and
235       "{}" instead of relying upon lexical (or dynamic) scoping and hidden
236       reference-counting to do the right thing behind the scenes.
237
238       In summary:
239
240           $AoA[$i] = [ @array ];      # usually best
241           $AoA[$i] = \@array;         # perilous; just how my() was that array?
242           @{ $AoA[$i] } = @array;     # way too tricky for most programmers
243

CAVEAT ON PRECEDENCE

245       Speaking of things like "@{$AoA[$i]}", the following are actually the
246       same thing:
247
248           $aref->[2][2]       # clear
249           $$aref[2][2]        # confusing
250
251       That's because Perl's precedence rules on its five prefix dereferencers
252       (which look like someone swearing: "$ @ * % &") make them bind more
253       tightly than the postfix subscripting brackets or braces!  This will no
254       doubt come as a great shock to the C or C++ programmer, who is quite
255       accustomed to using *a[i] to mean what's pointed to by the i'th element
256       of "a".  That is, they first take the subscript, and only then
257       dereference the thing at that subscript.  That's fine in C, but this
258       isn't C.
259
260       The seemingly equivalent construct in Perl, $$aref[$i] first does the
261       deref of $aref, making it take $aref as a reference to an array, and
262       then dereference that, and finally tell you the i'th value of the array
263       pointed to by $AoA. If you wanted the C notion, you'd have to write
264       "${$AoA[$i]}" to force the $AoA[$i] to get evaluated first before the
265       leading "$" dereferencer.
266

WHY YOU SHOULD ALWAYS "use strict"

268       If this is starting to sound scarier than it's worth, relax.  Perl has
269       some features to help you avoid its most common pitfalls.  The best way
270       to avoid getting confused is to start every program like this:
271
272           #!/usr/bin/perl -w
273           use strict;
274
275       This way, you'll be forced to declare all your variables with my() and
276       also disallow accidental "symbolic dereferencing".  Therefore if you'd
277       done this:
278
279           my $aref = [
280               [ "fred", "barney", "pebbles", "bambam", "dino", ],
281               [ "homer", "bart", "marge", "maggie", ],
282               [ "george", "jane", "elroy", "judy", ],
283           ];
284
285           print $aref[2][2];
286
287       The compiler would immediately flag that as an error at compile time,
288       because you were accidentally accessing @aref, an undeclared variable,
289       and it would thereby remind you to write instead:
290
291           print $aref->[2][2]
292

DEBUGGING

294       Before version 5.002, the standard Perl debugger didn't do a very nice
295       job of printing out complex data structures.  With 5.002 or above, the
296       debugger includes several new features, including command line editing
297       as well as the "x" command to dump out complex data structures.  For
298       example, given the assignment to $AoA above, here's the debugger
299       output:
300
301           DB<1> x $AoA
302           $AoA = ARRAY(0x13b5a0)
303              0  ARRAY(0x1f0a24)
304                 0  'fred'
305                 1  'barney'
306                 2  'pebbles'
307                 3  'bambam'
308                 4  'dino'
309              1  ARRAY(0x13b558)
310                 0  'homer'
311                 1  'bart'
312                 2  'marge'
313                 3  'maggie'
314              2  ARRAY(0x13b540)
315                 0  'george'
316                 1  'jane'
317                 2  'elroy'
318                 3  'judy'
319

CODE EXAMPLES

321       Presented with little comment (these will get their own manpages
322       someday) here are short code examples illustrating access of various
323       types of data structures.
324

ARRAYS OF ARRAYS

326   Declaration of an ARRAY OF ARRAYS
327        @AoA = (
328               [ "fred", "barney" ],
329               [ "george", "jane", "elroy" ],
330               [ "homer", "marge", "bart" ],
331             );
332
333   Generation of an ARRAY OF ARRAYS
334        # reading from file
335        while ( <> ) {
336            push @AoA, [ split ];
337        }
338
339        # calling a function
340        for $i ( 1 .. 10 ) {
341            $AoA[$i] = [ somefunc($i) ];
342        }
343
344        # using temp vars
345        for $i ( 1 .. 10 ) {
346            @tmp = somefunc($i);
347            $AoA[$i] = [ @tmp ];
348        }
349
350        # add to an existing row
351        push @{ $AoA[0] }, "wilma", "betty";
352
353   Access and Printing of an ARRAY OF ARRAYS
354        # one element
355        $AoA[0][0] = "Fred";
356
357        # another element
358        $AoA[1][1] =~ s/(\w)/\u$1/;
359
360        # print the whole thing with refs
361        for $aref ( @AoA ) {
362            print "\t [ @$aref ],\n";
363        }
364
365        # print the whole thing with indices
366        for $i ( 0 .. $#AoA ) {
367            print "\t [ @{$AoA[$i]} ],\n";
368        }
369
370        # print the whole thing one at a time
371        for $i ( 0 .. $#AoA ) {
372            for $j ( 0 .. $#{ $AoA[$i] } ) {
373                print "elt $i $j is $AoA[$i][$j]\n";
374            }
375        }
376

HASHES OF ARRAYS

378   Declaration of a HASH OF ARRAYS
379        %HoA = (
380               flintstones        => [ "fred", "barney" ],
381               jetsons            => [ "george", "jane", "elroy" ],
382               simpsons           => [ "homer", "marge", "bart" ],
383             );
384
385   Generation of a HASH OF ARRAYS
386        # reading from file
387        # flintstones: fred barney wilma dino
388        while ( <> ) {
389            next unless s/^(.*?):\s*//;
390            $HoA{$1} = [ split ];
391        }
392
393        # reading from file; more temps
394        # flintstones: fred barney wilma dino
395        while ( $line = <> ) {
396            ($who, $rest) = split /:\s*/, $line, 2;
397            @fields = split ' ', $rest;
398            $HoA{$who} = [ @fields ];
399        }
400
401        # calling a function that returns a list
402        for $group ( "simpsons", "jetsons", "flintstones" ) {
403            $HoA{$group} = [ get_family($group) ];
404        }
405
406        # likewise, but using temps
407        for $group ( "simpsons", "jetsons", "flintstones" ) {
408            @members = get_family($group);
409            $HoA{$group} = [ @members ];
410        }
411
412        # append new members to an existing family
413        push @{ $HoA{"flintstones"} }, "wilma", "betty";
414
415   Access and Printing of a HASH OF ARRAYS
416        # one element
417        $HoA{flintstones}[0] = "Fred";
418
419        # another element
420        $HoA{simpsons}[1] =~ s/(\w)/\u$1/;
421
422        # print the whole thing
423        foreach $family ( keys %HoA ) {
424            print "$family: @{ $HoA{$family} }\n"
425        }
426
427        # print the whole thing with indices
428        foreach $family ( keys %HoA ) {
429            print "family: ";
430            foreach $i ( 0 .. $#{ $HoA{$family} } ) {
431                print " $i = $HoA{$family}[$i]";
432            }
433            print "\n";
434        }
435
436        # print the whole thing sorted by number of members
437        foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
438            print "$family: @{ $HoA{$family} }\n"
439        }
440
441        # print the whole thing sorted by number of members and name
442        foreach $family ( sort {
443                                   @{$HoA{$b}} <=> @{$HoA{$a}}
444                                               ||
445                                           $a cmp $b
446                   } keys %HoA )
447        {
448            print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n";
449        }
450

ARRAYS OF HASHES

452   Declaration of an ARRAY OF HASHES
453        @AoH = (
454               {
455                   Lead     => "fred",
456                   Friend   => "barney",
457               },
458               {
459                   Lead     => "george",
460                   Wife     => "jane",
461                   Son      => "elroy",
462               },
463               {
464                   Lead     => "homer",
465                   Wife     => "marge",
466                   Son      => "bart",
467               }
468         );
469
470   Generation of an ARRAY OF HASHES
471        # reading from file
472        # format: LEAD=fred FRIEND=barney
473        while ( <> ) {
474            $rec = {};
475            for $field ( split ) {
476                ($key, $value) = split /=/, $field;
477                $rec->{$key} = $value;
478            }
479            push @AoH, $rec;
480        }
481
482
483        # reading from file
484        # format: LEAD=fred FRIEND=barney
485        # no temp
486        while ( <> ) {
487            push @AoH, { split /[\s+=]/ };
488        }
489
490        # calling a function  that returns a key/value pair list, like
491        # "lead","fred","daughter","pebbles"
492        while ( %fields = getnextpairset() ) {
493            push @AoH, { %fields };
494        }
495
496        # likewise, but using no temp vars
497        while (<>) {
498            push @AoH, { parsepairs($_) };
499        }
500
501        # add key/value to an element
502        $AoH[0]{pet} = "dino";
503        $AoH[2]{pet} = "santa's little helper";
504
505   Access and Printing of an ARRAY OF HASHES
506        # one element
507        $AoH[0]{lead} = "fred";
508
509        # another element
510        $AoH[1]{lead} =~ s/(\w)/\u$1/;
511
512        # print the whole thing with refs
513        for $href ( @AoH ) {
514            print "{ ";
515            for $role ( keys %$href ) {
516                print "$role=$href->{$role} ";
517            }
518            print "}\n";
519        }
520
521        # print the whole thing with indices
522        for $i ( 0 .. $#AoH ) {
523            print "$i is { ";
524            for $role ( keys %{ $AoH[$i] } ) {
525                print "$role=$AoH[$i]{$role} ";
526            }
527            print "}\n";
528        }
529
530        # print the whole thing one at a time
531        for $i ( 0 .. $#AoH ) {
532            for $role ( keys %{ $AoH[$i] } ) {
533                print "elt $i $role is $AoH[$i]{$role}\n";
534            }
535        }
536

HASHES OF HASHES

538   Declaration of a HASH OF HASHES
539        %HoH = (
540               flintstones => {
541                       lead      => "fred",
542                       pal       => "barney",
543               },
544               jetsons     => {
545                       lead      => "george",
546                       wife      => "jane",
547                       "his boy" => "elroy",
548               },
549               simpsons    => {
550                       lead      => "homer",
551                       wife      => "marge",
552                       kid       => "bart",
553               },
554        );
555
556   Generation of a HASH OF HASHES
557        # reading from file
558        # flintstones: lead=fred pal=barney wife=wilma pet=dino
559        while ( <> ) {
560            next unless s/^(.*?):\s*//;
561            $who = $1;
562            for $field ( split ) {
563                ($key, $value) = split /=/, $field;
564                $HoH{$who}{$key} = $value;
565            }
566
567
568        # reading from file; more temps
569        while ( <> ) {
570            next unless s/^(.*?):\s*//;
571            $who = $1;
572            $rec = {};
573            $HoH{$who} = $rec;
574            for $field ( split ) {
575                ($key, $value) = split /=/, $field;
576                $rec->{$key} = $value;
577            }
578        }
579
580        # calling a function  that returns a key,value hash
581        for $group ( "simpsons", "jetsons", "flintstones" ) {
582            $HoH{$group} = { get_family($group) };
583        }
584
585        # likewise, but using temps
586        for $group ( "simpsons", "jetsons", "flintstones" ) {
587            %members = get_family($group);
588            $HoH{$group} = { %members };
589        }
590
591        # append new members to an existing family
592        %new_folks = (
593            wife => "wilma",
594            pet  => "dino",
595        );
596
597        for $what (keys %new_folks) {
598            $HoH{flintstones}{$what} = $new_folks{$what};
599        }
600
601   Access and Printing of a HASH OF HASHES
602        # one element
603        $HoH{flintstones}{wife} = "wilma";
604
605        # another element
606        $HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
607
608        # print the whole thing
609        foreach $family ( keys %HoH ) {
610            print "$family: { ";
611            for $role ( keys %{ $HoH{$family} } ) {
612                print "$role=$HoH{$family}{$role} ";
613            }
614            print "}\n";
615        }
616
617        # print the whole thing  somewhat sorted
618        foreach $family ( sort keys %HoH ) {
619            print "$family: { ";
620            for $role ( sort keys %{ $HoH{$family} } ) {
621                print "$role=$HoH{$family}{$role} ";
622            }
623            print "}\n";
624        }
625
626
627        # print the whole thing sorted by number of members
628        foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) {
629            print "$family: { ";
630            for $role ( sort keys %{ $HoH{$family} } ) {
631                print "$role=$HoH{$family}{$role} ";
632            }
633            print "}\n";
634        }
635
636        # establish a sort order (rank) for each role
637        $i = 0;
638        for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
639
640        # now print the whole thing sorted by number of members
641        foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) {
642            print "$family: { ";
643            # and print these according to rank order
644            for $role ( sort { $rank{$a} <=> $rank{$b} }  keys %{ $HoH{$family} } ) {
645                print "$role=$HoH{$family}{$role} ";
646            }
647            print "}\n";
648        }
649

MORE ELABORATE RECORDS

651   Declaration of MORE ELABORATE RECORDS
652       Here's a sample showing how to create and use a record whose fields are
653       of many different sorts:
654
655            $rec = {
656                TEXT      => $string,
657                SEQUENCE  => [ @old_values ],
658                LOOKUP    => { %some_table },
659                THATCODE  => \&some_function,
660                THISCODE  => sub { $_[0] ** $_[1] },
661                HANDLE    => \*STDOUT,
662            };
663
664            print $rec->{TEXT};
665
666            print $rec->{SEQUENCE}[0];
667            $last = pop @ { $rec->{SEQUENCE} };
668
669            print $rec->{LOOKUP}{"key"};
670            ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
671
672            $answer = $rec->{THATCODE}->($arg);
673            $answer = $rec->{THISCODE}->($arg1, $arg2);
674
675            # careful of extra block braces on fh ref
676            print { $rec->{HANDLE} } "a string\n";
677
678            use FileHandle;
679            $rec->{HANDLE}->autoflush(1);
680            $rec->{HANDLE}->print(" a string\n");
681
682   Declaration of a HASH OF COMPLEX RECORDS
683            %TV = (
684               flintstones => {
685                   series   => "flintstones",
686                   nights   => [ qw(monday thursday friday) ],
687                   members  => [
688                       { name => "fred",    role => "lead", age  => 36, },
689                       { name => "wilma",   role => "wife", age  => 31, },
690                       { name => "pebbles", role => "kid",  age  =>  4, },
691                   ],
692               },
693
694               jetsons     => {
695                   series   => "jetsons",
696                   nights   => [ qw(wednesday saturday) ],
697                   members  => [
698                       { name => "george",  role => "lead", age  => 41, },
699                       { name => "jane",    role => "wife", age  => 39, },
700                       { name => "elroy",   role => "kid",  age  =>  9, },
701                   ],
702                },
703
704               simpsons    => {
705                   series   => "simpsons",
706                   nights   => [ qw(monday) ],
707                   members  => [
708                       { name => "homer", role => "lead", age  => 34, },
709                       { name => "marge", role => "wife", age => 37, },
710                       { name => "bart",  role => "kid",  age  =>  11, },
711                   ],
712                },
713             );
714
715   Generation of a HASH OF COMPLEX RECORDS
716            # reading from file
717            # this is most easily done by having the file itself be
718            # in the raw data format as shown above.  perl is happy
719            # to parse complex data structures if declared as data, so
720            # sometimes it's easiest to do that
721
722            # here's a piece by piece build up
723            $rec = {};
724            $rec->{series} = "flintstones";
725            $rec->{nights} = [ find_days() ];
726
727            @members = ();
728            # assume this file in field=value syntax
729            while (<>) {
730                %fields = split /[\s=]+/;
731                push @members, { %fields };
732            }
733            $rec->{members} = [ @members ];
734
735            # now remember the whole thing
736            $TV{ $rec->{series} } = $rec;
737
738            ###########################################################
739            # now, you might want to make interesting extra fields that
740            # include pointers back into the same data structure so if
741            # change one piece, it changes everywhere, like for example
742            # if you wanted a {kids} field that was a reference
743            # to an array of the kids' records without having duplicate
744            # records and thus update problems.
745            ###########################################################
746            foreach $family (keys %TV) {
747                $rec = $TV{$family}; # temp pointer
748                @kids = ();
749                for $person ( @{ $rec->{members} } ) {
750                    if ($person->{role} =~ /kid|son|daughter/) {
751                        push @kids, $person;
752                    }
753                }
754                # REMEMBER: $rec and $TV{$family} point to same data!!
755                $rec->{kids} = [ @kids ];
756            }
757
758            # you copied the array, but the array itself contains pointers
759            # to uncopied objects. this means that if you make bart get
760            # older via
761
762            $TV{simpsons}{kids}[0]{age}++;
763
764            # then this would also change in
765            print $TV{simpsons}{members}[2]{age};
766
767            # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
768            # both point to the same underlying anonymous hash table
769
770            # print the whole thing
771            foreach $family ( keys %TV ) {
772                print "the $family";
773                print " is on during @{ $TV{$family}{nights} }\n";
774                print "its members are:\n";
775                for $who ( @{ $TV{$family}{members} } ) {
776                    print " $who->{name} ($who->{role}), age $who->{age}\n";
777                }
778                print "it turns out that $TV{$family}{lead} has ";
779                print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
780                print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
781                print "\n";
782            }
783

Database Ties

785       You cannot easily tie a multilevel data structure (such as a hash of
786       hashes) to a dbm file.  The first problem is that all but GDBM and
787       Berkeley DB have size limitations, but beyond that, you also have
788       problems with how references are to be represented on disk.  One
789       experimental module that does partially attempt to address this need is
790       the MLDBM module.  Check your nearest CPAN site as described in
791       perlmodlib for source code to MLDBM.
792

SEE ALSO

794       perlref(1), perllol(1), perldata(1), perlobj(1)
795

AUTHOR

797       Tom Christiansen <tchrist@perl.com>
798
799       Last update: Wed Oct 23 04:57:50 MET DST 1996
800
801
802
803perl v5.10.1                      2009-04-11                        PERLDSC(1)
Impressum