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 perlref.  Briefly,
83       references are rather like pointers that know what they point to.
84       (Objects are also a kind of reference, but we won't be needing them
85       right away--if ever.)  This means that when you have something which
86       looks to you like an access to a two-or-more-dimensional array and/or
87       hash, what's really going on is that the base type is merely a one-
88       dimensional entity that contains references to the next level.  It's
89       just that you can use it as though it were a two-dimensional one.  This
90       is actually the way almost all C multidimensional arrays work as well.
91
92           $array[7][12]                       # array of arrays
93           $array[7]{string}                   # array of hashes
94           $hash{string}[7]                    # hash of arrays
95           $hash{string}{'another string'}     # hash of hashes
96
97       Now, because the top level contains only references, if you try to
98       print out your array in with a simple print() function, you'll get
99       something that doesn't look very nice, like this:
100
101           @AoA = ( [2, 3], [4, 5, 7], [0] );
102           print $AoA[1][2];
103         7
104           print @AoA;
105         ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
106
107       That's because Perl doesn't (ever) implicitly dereference your
108       variables.  If you want to get at the thing a reference is referring
109       to, then you have to do this yourself using either prefix typing
110       indicators, like "${$blah}", "@{$blah}", "@{$blah[$i]}", or else
111       postfix pointer arrows, like "$a->[3]", "$h->{fred}", or even
112       "$ob->method()->[3]".
113

COMMON MISTAKES

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

CAVEAT ON PRECEDENCE

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

WHY YOU SHOULD ALWAYS "use strict"

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

DEBUGGING

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

CODE EXAMPLES

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

ARRAYS OF ARRAYS

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

HASHES OF ARRAYS

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

ARRAYS OF HASHES

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

HASHES OF HASHES

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

MORE ELABORATE RECORDS

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

Database Ties

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

SEE ALSO

793       perlref, perllol, perldata, perlobj
794

AUTHOR

796       Tom Christiansen <tchrist@perl.com>
797
798       Last update: Wed Oct 23 04:57:50 MET DST 1996
799
800
801
802perl v5.12.4                      2011-06-01                        PERLDSC(1)
Impressum