Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

832 lines
25 KiB

  1. =head1 NAME
  2. perldsc - Perl Data Structures Cookbook
  3. =head1 DESCRIPTION
  4. The single feature most sorely lacking in the Perl programming language
  5. prior to its 5.0 release was complex data structures. Even without direct
  6. language support, some valiant programmers did manage to emulate them, but
  7. it was hard work and not for the faint of heart. You could occasionally
  8. get away with the C<$m{$AoA,$b}> notation borrowed from B<awk> in which the
  9. keys are actually more like a single concatenated string C<"$AoA$b">, but
  10. traversal and sorting were difficult. More desperate programmers even
  11. hacked Perl's internal symbol table directly, a strategy that proved hard
  12. to develop and maintain--to put it mildly.
  13. The 5.0 release of Perl let us have complex data structures. You
  14. may now write something like this and all of a sudden, you'd have a array
  15. with three dimensions!
  16. for $x (1 .. 10) {
  17. for $y (1 .. 10) {
  18. for $z (1 .. 10) {
  19. $AoA[$x][$y][$z] =
  20. $x ** $y + $z;
  21. }
  22. }
  23. }
  24. Alas, however simple this may appear, underneath it's a much more
  25. elaborate construct than meets the eye!
  26. How do you print it out? Why can't you say just C<print @AoA>? How do
  27. you sort it? How can you pass it to a function or get one of these back
  28. from a function? Is is an object? Can you save it to disk to read
  29. back later? How do you access whole rows or columns of that matrix? Do
  30. all the values have to be numeric?
  31. As you see, it's quite easy to become confused. While some small portion
  32. of the blame for this can be attributed to the reference-based
  33. implementation, it's really more due to a lack of existing documentation with
  34. examples designed for the beginner.
  35. This document is meant to be a detailed but understandable treatment of the
  36. many different sorts of data structures you might want to develop. It
  37. should also serve as a cookbook of examples. That way, when you need to
  38. create one of these complex data structures, you can just pinch, pilfer, or
  39. purloin a drop-in example from here.
  40. Let's look at each of these possible constructs in detail. There are separate
  41. sections on each of the following:
  42. =over 5
  43. =item * arrays of arrays
  44. =item * hashes of arrays
  45. =item * arrays of hashes
  46. =item * hashes of hashes
  47. =item * more elaborate constructs
  48. =back
  49. But for now, let's look at general issues common to all
  50. these types of data structures.
  51. =head1 REFERENCES
  52. The most important thing to understand about all data structures in Perl
  53. -- including multidimensional arrays--is that even though they might
  54. appear otherwise, Perl C<@ARRAY>s and C<%HASH>es are all internally
  55. one-dimensional. They can hold only scalar values (meaning a string,
  56. number, or a reference). They cannot directly contain other arrays or
  57. hashes, but instead contain I<references> to other arrays or hashes.
  58. You can't use a reference to a array or hash in quite the same way that you
  59. would a real array or hash. For C or C++ programmers unused to
  60. distinguishing between arrays and pointers to the same, this can be
  61. confusing. If so, just think of it as the difference between a structure
  62. and a pointer to a structure.
  63. You can (and should) read more about references in the perlref(1) man
  64. page. Briefly, references are rather like pointers that know what they
  65. point to. (Objects are also a kind of reference, but we won't be needing
  66. them right away--if ever.) This means that when you have something which
  67. looks to you like an access to a two-or-more-dimensional array and/or hash,
  68. what's really going on is that the base type is
  69. merely a one-dimensional entity that contains references to the next
  70. level. It's just that you can I<use> it as though it were a
  71. two-dimensional one. This is actually the way almost all C
  72. multidimensional arrays work as well.
  73. $array[7][12] # array of arrays
  74. $array[7]{string} # array of hashes
  75. $hash{string}[7] # hash of arrays
  76. $hash{string}{'another string'} # hash of hashes
  77. Now, because the top level contains only references, if you try to print
  78. out your array in with a simple print() function, you'll get something
  79. that doesn't look very nice, like this:
  80. @AoA = ( [2, 3], [4, 5, 7], [0] );
  81. print $AoA[1][2];
  82. 7
  83. print @AoA;
  84. ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
  85. That's because Perl doesn't (ever) implicitly dereference your variables.
  86. If you want to get at the thing a reference is referring to, then you have
  87. to do this yourself using either prefix typing indicators, like
  88. C<${$blah}>, C<@{$blah}>, C<@{$blah[$i]}>, or else postfix pointer arrows,
  89. like C<$a-E<gt>[3]>, C<$h-E<gt>{fred}>, or even C<$ob-E<gt>method()-E<gt>[3]>.
  90. =head1 COMMON MISTAKES
  91. The two most common mistakes made in constructing something like
  92. an array of arrays is either accidentally counting the number of
  93. elements or else taking a reference to the same memory location
  94. repeatedly. Here's the case where you just get the count instead
  95. of a nested array:
  96. for $i (1..10) {
  97. @array = somefunc($i);
  98. $AoA[$i] = @array; # WRONG!
  99. }
  100. That's just the simple case of assigning an array to a scalar and getting
  101. its element count. If that's what you really and truly want, then you
  102. might do well to consider being a tad more explicit about it, like this:
  103. for $i (1..10) {
  104. @array = somefunc($i);
  105. $counts[$i] = scalar @array;
  106. }
  107. Here's the case of taking a reference to the same memory location
  108. again and again:
  109. for $i (1..10) {
  110. @array = somefunc($i);
  111. $AoA[$i] = \@array; # WRONG!
  112. }
  113. So, what's the big problem with that? It looks right, doesn't it?
  114. After all, I just told you that you need an array of references, so by
  115. golly, you've made me one!
  116. Unfortunately, while this is true, it's still broken. All the references
  117. in @AoA refer to the I<very same place>, and they will therefore all hold
  118. whatever was last in @array! It's similar to the problem demonstrated in
  119. the following C program:
  120. #include <pwd.h>
  121. main() {
  122. struct passwd *getpwnam(), *rp, *dp;
  123. rp = getpwnam("root");
  124. dp = getpwnam("daemon");
  125. printf("daemon name is %s\nroot name is %s\n",
  126. dp->pw_name, rp->pw_name);
  127. }
  128. Which will print
  129. daemon name is daemon
  130. root name is daemon
  131. The problem is that both C<rp> and C<dp> are pointers to the same location
  132. in memory! In C, you'd have to remember to malloc() yourself some new
  133. memory. In Perl, you'll want to use the array constructor C<[]> or the
  134. hash constructor C<{}> instead. Here's the right way to do the preceding
  135. broken code fragments:
  136. for $i (1..10) {
  137. @array = somefunc($i);
  138. $AoA[$i] = [ @array ];
  139. }
  140. The square brackets make a reference to a new array with a I<copy>
  141. of what's in @array at the time of the assignment. This is what
  142. you want.
  143. Note that this will produce something similar, but it's
  144. much harder to read:
  145. for $i (1..10) {
  146. @array = 0 .. $i;
  147. @{$AoA[$i]} = @array;
  148. }
  149. Is it the same? Well, maybe so--and maybe not. The subtle difference
  150. is that when you assign something in square brackets, you know for sure
  151. it's always a brand new reference with a new I<copy> of the data.
  152. Something else could be going on in this new case with the C<@{$AoA[$i]}}>
  153. dereference on the left-hand-side of the assignment. It all depends on
  154. whether C<$AoA[$i]> had been undefined to start with, or whether it
  155. already contained a reference. If you had already populated @AoA with
  156. references, as in
  157. $AoA[3] = \@another_array;
  158. Then the assignment with the indirection on the left-hand-side would
  159. use the existing reference that was already there:
  160. @{$AoA[3]} = @array;
  161. Of course, this I<would> have the "interesting" effect of clobbering
  162. @another_array. (Have you ever noticed how when a programmer says
  163. something is "interesting", that rather than meaning "intriguing",
  164. they're disturbingly more apt to mean that it's "annoying",
  165. "difficult", or both? :-)
  166. So just remember always to use the array or hash constructors with C<[]>
  167. or C<{}>, and you'll be fine, although it's not always optimally
  168. efficient.
  169. Surprisingly, the following dangerous-looking construct will
  170. actually work out fine:
  171. for $i (1..10) {
  172. my @array = somefunc($i);
  173. $AoA[$i] = \@array;
  174. }
  175. That's because my() is more of a run-time statement than it is a
  176. compile-time declaration I<per se>. This means that the my() variable is
  177. remade afresh each time through the loop. So even though it I<looks> as
  178. though you stored the same variable reference each time, you actually did
  179. not! This is a subtle distinction that can produce more efficient code at
  180. the risk of misleading all but the most experienced of programmers. So I
  181. usually advise against teaching it to beginners. In fact, except for
  182. passing arguments to functions, I seldom like to see the gimme-a-reference
  183. operator (backslash) used much at all in code. Instead, I advise
  184. beginners that they (and most of the rest of us) should try to use the
  185. much more easily understood constructors C<[]> and C<{}> instead of
  186. relying upon lexical (or dynamic) scoping and hidden reference-counting to
  187. do the right thing behind the scenes.
  188. In summary:
  189. $AoA[$i] = [ @array ]; # usually best
  190. $AoA[$i] = \@array; # perilous; just how my() was that array?
  191. @{ $AoA[$i] } = @array; # way too tricky for most programmers
  192. =head1 CAVEAT ON PRECEDENCE
  193. Speaking of things like C<@{$AoA[$i]}>, the following are actually the
  194. same thing:
  195. $aref->[2][2] # clear
  196. $$aref[2][2] # confusing
  197. That's because Perl's precedence rules on its five prefix dereferencers
  198. (which look like someone swearing: C<$ @ * % &>) make them bind more
  199. tightly than the postfix subscripting brackets or braces! This will no
  200. doubt come as a great shock to the C or C++ programmer, who is quite
  201. accustomed to using C<*a[i]> to mean what's pointed to by the I<i'th>
  202. element of C<a>. That is, they first take the subscript, and only then
  203. dereference the thing at that subscript. That's fine in C, but this isn't C.
  204. The seemingly equivalent construct in Perl, C<$$aref[$i]> first does
  205. the deref of $aref, making it take $aref as a reference to an
  206. array, and then dereference that, and finally tell you the I<i'th> value
  207. of the array pointed to by $AoA. If you wanted the C notion, you'd have to
  208. write C<${$AoA[$i]}> to force the C<$AoA[$i]> to get evaluated first
  209. before the leading C<$> dereferencer.
  210. =head1 WHY YOU SHOULD ALWAYS C<use strict>
  211. If this is starting to sound scarier than it's worth, relax. Perl has
  212. some features to help you avoid its most common pitfalls. The best
  213. way to avoid getting confused is to start every program like this:
  214. #!/usr/bin/perl -w
  215. use strict;
  216. This way, you'll be forced to declare all your variables with my() and
  217. also disallow accidental "symbolic dereferencing". Therefore if you'd done
  218. this:
  219. my $aref = [
  220. [ "fred", "barney", "pebbles", "bambam", "dino", ],
  221. [ "homer", "bart", "marge", "maggie", ],
  222. [ "george", "jane", "elroy", "judy", ],
  223. ];
  224. print $aref[2][2];
  225. The compiler would immediately flag that as an error I<at compile time>,
  226. because you were accidentally accessing C<@aref>, an undeclared
  227. variable, and it would thereby remind you to write instead:
  228. print $aref->[2][2]
  229. =head1 DEBUGGING
  230. Before version 5.002, the standard Perl debugger didn't do a very nice job of
  231. printing out complex data structures. With 5.002 or above, the
  232. debugger includes several new features, including command line editing as
  233. well as the C<x> command to dump out complex data structures. For
  234. example, given the assignment to $AoA above, here's the debugger output:
  235. DB<1> x $AoA
  236. $AoA = ARRAY(0x13b5a0)
  237. 0 ARRAY(0x1f0a24)
  238. 0 'fred'
  239. 1 'barney'
  240. 2 'pebbles'
  241. 3 'bambam'
  242. 4 'dino'
  243. 1 ARRAY(0x13b558)
  244. 0 'homer'
  245. 1 'bart'
  246. 2 'marge'
  247. 3 'maggie'
  248. 2 ARRAY(0x13b540)
  249. 0 'george'
  250. 1 'jane'
  251. 2 'elroy'
  252. 3 'judy'
  253. =head1 CODE EXAMPLES
  254. Presented with little comment (these will get their own manpages someday)
  255. here are short code examples illustrating access of various
  256. types of data structures.
  257. =head1 ARRAYS OF ARRAYS
  258. =head2 Declaration of a ARRAY OF ARRAYS
  259. @AoA = (
  260. [ "fred", "barney" ],
  261. [ "george", "jane", "elroy" ],
  262. [ "homer", "marge", "bart" ],
  263. );
  264. =head2 Generation of a ARRAY OF ARRAYS
  265. # reading from file
  266. while ( <> ) {
  267. push @AoA, [ split ];
  268. }
  269. # calling a function
  270. for $i ( 1 .. 10 ) {
  271. $AoA[$i] = [ somefunc($i) ];
  272. }
  273. # using temp vars
  274. for $i ( 1 .. 10 ) {
  275. @tmp = somefunc($i);
  276. $AoA[$i] = [ @tmp ];
  277. }
  278. # add to an existing row
  279. push @{ $AoA[0] }, "wilma", "betty";
  280. =head2 Access and Printing of a ARRAY OF ARRAYS
  281. # one element
  282. $AoA[0][0] = "Fred";
  283. # another element
  284. $AoA[1][1] =~ s/(\w)/\u$1/;
  285. # print the whole thing with refs
  286. for $aref ( @AoA ) {
  287. print "\t [ @$aref ],\n";
  288. }
  289. # print the whole thing with indices
  290. for $i ( 0 .. $#AoA ) {
  291. print "\t [ @{$AoA[$i]} ],\n";
  292. }
  293. # print the whole thing one at a time
  294. for $i ( 0 .. $#AoA ) {
  295. for $j ( 0 .. $#{ $AoA[$i] } ) {
  296. print "elt $i $j is $AoA[$i][$j]\n";
  297. }
  298. }
  299. =head1 HASHES OF ARRAYS
  300. =head2 Declaration of a HASH OF ARRAYS
  301. %HoA = (
  302. flintstones => [ "fred", "barney" ],
  303. jetsons => [ "george", "jane", "elroy" ],
  304. simpsons => [ "homer", "marge", "bart" ],
  305. );
  306. =head2 Generation of a HASH OF ARRAYS
  307. # reading from file
  308. # flintstones: fred barney wilma dino
  309. while ( <> ) {
  310. next unless s/^(.*?):\s*//;
  311. $HoA{$1} = [ split ];
  312. }
  313. # reading from file; more temps
  314. # flintstones: fred barney wilma dino
  315. while ( $line = <> ) {
  316. ($who, $rest) = split /:\s*/, $line, 2;
  317. @fields = split ' ', $rest;
  318. $HoA{$who} = [ @fields ];
  319. }
  320. # calling a function that returns a list
  321. for $group ( "simpsons", "jetsons", "flintstones" ) {
  322. $HoA{$group} = [ get_family($group) ];
  323. }
  324. # likewise, but using temps
  325. for $group ( "simpsons", "jetsons", "flintstones" ) {
  326. @members = get_family($group);
  327. $HoA{$group} = [ @members ];
  328. }
  329. # append new members to an existing family
  330. push @{ $HoA{"flintstones"} }, "wilma", "betty";
  331. =head2 Access and Printing of a HASH OF ARRAYS
  332. # one element
  333. $HoA{flintstones}[0] = "Fred";
  334. # another element
  335. $HoA{simpsons}[1] =~ s/(\w)/\u$1/;
  336. # print the whole thing
  337. foreach $family ( keys %HoA ) {
  338. print "$family: @{ $HoA{$family} }\n"
  339. }
  340. # print the whole thing with indices
  341. foreach $family ( keys %HoA ) {
  342. print "family: ";
  343. foreach $i ( 0 .. $#{ $HoA{$family} } ) {
  344. print " $i = $HoA{$family}[$i]";
  345. }
  346. print "\n";
  347. }
  348. # print the whole thing sorted by number of members
  349. foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
  350. print "$family: @{ $HoA{$family} }\n"
  351. }
  352. # print the whole thing sorted by number of members and name
  353. foreach $family ( sort {
  354. @{$HoA{$b}} <=> @{$HoA{$a}}
  355. ||
  356. $a cmp $b
  357. } keys %HoA )
  358. {
  359. print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n";
  360. }
  361. =head1 ARRAYS OF HASHES
  362. =head2 Declaration of a ARRAY OF HASHES
  363. @AoH = (
  364. {
  365. Lead => "fred",
  366. Friend => "barney",
  367. },
  368. {
  369. Lead => "george",
  370. Wife => "jane",
  371. Son => "elroy",
  372. },
  373. {
  374. Lead => "homer",
  375. Wife => "marge",
  376. Son => "bart",
  377. }
  378. );
  379. =head2 Generation of a ARRAY OF HASHES
  380. # reading from file
  381. # format: LEAD=fred FRIEND=barney
  382. while ( <> ) {
  383. $rec = {};
  384. for $field ( split ) {
  385. ($key, $value) = split /=/, $field;
  386. $rec->{$key} = $value;
  387. }
  388. push @AoH, $rec;
  389. }
  390. # reading from file
  391. # format: LEAD=fred FRIEND=barney
  392. # no temp
  393. while ( <> ) {
  394. push @AoH, { split /[\s+=]/ };
  395. }
  396. # calling a function that returns a key/value pair list, like
  397. # "lead","fred","daughter","pebbles"
  398. while ( %fields = getnextpairset() ) {
  399. push @AoH, { %fields };
  400. }
  401. # likewise, but using no temp vars
  402. while (<>) {
  403. push @AoH, { parsepairs($_) };
  404. }
  405. # add key/value to an element
  406. $AoH[0]{pet} = "dino";
  407. $AoH[2]{pet} = "santa's little helper";
  408. =head2 Access and Printing of a ARRAY OF HASHES
  409. # one element
  410. $AoH[0]{lead} = "fred";
  411. # another element
  412. $AoH[1]{lead} =~ s/(\w)/\u$1/;
  413. # print the whole thing with refs
  414. for $href ( @AoH ) {
  415. print "{ ";
  416. for $role ( keys %$href ) {
  417. print "$role=$href->{$role} ";
  418. }
  419. print "}\n";
  420. }
  421. # print the whole thing with indices
  422. for $i ( 0 .. $#AoH ) {
  423. print "$i is { ";
  424. for $role ( keys %{ $AoH[$i] } ) {
  425. print "$role=$AoH[$i]{$role} ";
  426. }
  427. print "}\n";
  428. }
  429. # print the whole thing one at a time
  430. for $i ( 0 .. $#AoH ) {
  431. for $role ( keys %{ $AoH[$i] } ) {
  432. print "elt $i $role is $AoH[$i]{$role}\n";
  433. }
  434. }
  435. =head1 HASHES OF HASHES
  436. =head2 Declaration of a HASH OF HASHES
  437. %HoH = (
  438. flintstones => {
  439. lead => "fred",
  440. pal => "barney",
  441. },
  442. jetsons => {
  443. lead => "george",
  444. wife => "jane",
  445. "his boy" => "elroy",
  446. },
  447. simpsons => {
  448. lead => "homer",
  449. wife => "marge",
  450. kid => "bart",
  451. },
  452. );
  453. =head2 Generation of a HASH OF HASHES
  454. # reading from file
  455. # flintstones: lead=fred pal=barney wife=wilma pet=dino
  456. while ( <> ) {
  457. next unless s/^(.*?):\s*//;
  458. $who = $1;
  459. for $field ( split ) {
  460. ($key, $value) = split /=/, $field;
  461. $HoH{$who}{$key} = $value;
  462. }
  463. # reading from file; more temps
  464. while ( <> ) {
  465. next unless s/^(.*?):\s*//;
  466. $who = $1;
  467. $rec = {};
  468. $HoH{$who} = $rec;
  469. for $field ( split ) {
  470. ($key, $value) = split /=/, $field;
  471. $rec->{$key} = $value;
  472. }
  473. }
  474. # calling a function that returns a key,value hash
  475. for $group ( "simpsons", "jetsons", "flintstones" ) {
  476. $HoH{$group} = { get_family($group) };
  477. }
  478. # likewise, but using temps
  479. for $group ( "simpsons", "jetsons", "flintstones" ) {
  480. %members = get_family($group);
  481. $HoH{$group} = { %members };
  482. }
  483. # append new members to an existing family
  484. %new_folks = (
  485. wife => "wilma",
  486. pet => "dino",
  487. );
  488. for $what (keys %new_folks) {
  489. $HoH{flintstones}{$what} = $new_folks{$what};
  490. }
  491. =head2 Access and Printing of a HASH OF HASHES
  492. # one element
  493. $HoH{flintstones}{wife} = "wilma";
  494. # another element
  495. $HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
  496. # print the whole thing
  497. foreach $family ( keys %HoH ) {
  498. print "$family: { ";
  499. for $role ( keys %{ $HoH{$family} } ) {
  500. print "$role=$HoH{$family}{$role} ";
  501. }
  502. print "}\n";
  503. }
  504. # print the whole thing somewhat sorted
  505. foreach $family ( sort keys %HoH ) {
  506. print "$family: { ";
  507. for $role ( sort keys %{ $HoH{$family} } ) {
  508. print "$role=$HoH{$family}{$role} ";
  509. }
  510. print "}\n";
  511. }
  512. # print the whole thing sorted by number of members
  513. foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) {
  514. print "$family: { ";
  515. for $role ( sort keys %{ $HoH{$family} } ) {
  516. print "$role=$HoH{$family}{$role} ";
  517. }
  518. print "}\n";
  519. }
  520. # establish a sort order (rank) for each role
  521. $i = 0;
  522. for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
  523. # now print the whole thing sorted by number of members
  524. foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) {
  525. print "$family: { ";
  526. # and print these according to rank order
  527. for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) {
  528. print "$role=$HoH{$family}{$role} ";
  529. }
  530. print "}\n";
  531. }
  532. =head1 MORE ELABORATE RECORDS
  533. =head2 Declaration of MORE ELABORATE RECORDS
  534. Here's a sample showing how to create and use a record whose fields are of
  535. many different sorts:
  536. $rec = {
  537. TEXT => $string,
  538. SEQUENCE => [ @old_values ],
  539. LOOKUP => { %some_table },
  540. THATCODE => \&some_function,
  541. THISCODE => sub { $_[0] ** $_[1] },
  542. HANDLE => \*STDOUT,
  543. };
  544. print $rec->{TEXT};
  545. print $rec->{SEQUENCE}[0];
  546. $last = pop @ { $rec->{SEQUENCE} };
  547. print $rec->{LOOKUP}{"key"};
  548. ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
  549. $answer = $rec->{THATCODE}->($arg);
  550. $answer = $rec->{THISCODE}->($arg1, $arg2);
  551. # careful of extra block braces on fh ref
  552. print { $rec->{HANDLE} } "a string\n";
  553. use FileHandle;
  554. $rec->{HANDLE}->autoflush(1);
  555. $rec->{HANDLE}->print(" a string\n");
  556. =head2 Declaration of a HASH OF COMPLEX RECORDS
  557. %TV = (
  558. flintstones => {
  559. series => "flintstones",
  560. nights => [ qw(monday thursday friday) ],
  561. members => [
  562. { name => "fred", role => "lead", age => 36, },
  563. { name => "wilma", role => "wife", age => 31, },
  564. { name => "pebbles", role => "kid", age => 4, },
  565. ],
  566. },
  567. jetsons => {
  568. series => "jetsons",
  569. nights => [ qw(wednesday saturday) ],
  570. members => [
  571. { name => "george", role => "lead", age => 41, },
  572. { name => "jane", role => "wife", age => 39, },
  573. { name => "elroy", role => "kid", age => 9, },
  574. ],
  575. },
  576. simpsons => {
  577. series => "simpsons",
  578. nights => [ qw(monday) ],
  579. members => [
  580. { name => "homer", role => "lead", age => 34, },
  581. { name => "marge", role => "wife", age => 37, },
  582. { name => "bart", role => "kid", age => 11, },
  583. ],
  584. },
  585. );
  586. =head2 Generation of a HASH OF COMPLEX RECORDS
  587. # reading from file
  588. # this is most easily done by having the file itself be
  589. # in the raw data format as shown above. perl is happy
  590. # to parse complex data structures if declared as data, so
  591. # sometimes it's easiest to do that
  592. # here's a piece by piece build up
  593. $rec = {};
  594. $rec->{series} = "flintstones";
  595. $rec->{nights} = [ find_days() ];
  596. @members = ();
  597. # assume this file in field=value syntax
  598. while (<>) {
  599. %fields = split /[\s=]+/;
  600. push @members, { %fields };
  601. }
  602. $rec->{members} = [ @members ];
  603. # now remember the whole thing
  604. $TV{ $rec->{series} } = $rec;
  605. ###########################################################
  606. # now, you might want to make interesting extra fields that
  607. # include pointers back into the same data structure so if
  608. # change one piece, it changes everywhere, like for example
  609. # if you wanted a {kids} field that was a reference
  610. # to an array of the kids' records without having duplicate
  611. # records and thus update problems.
  612. ###########################################################
  613. foreach $family (keys %TV) {
  614. $rec = $TV{$family}; # temp pointer
  615. @kids = ();
  616. for $person ( @{ $rec->{members} } ) {
  617. if ($person->{role} =~ /kid|son|daughter/) {
  618. push @kids, $person;
  619. }
  620. }
  621. # REMEMBER: $rec and $TV{$family} point to same data!!
  622. $rec->{kids} = [ @kids ];
  623. }
  624. # you copied the array, but the array itself contains pointers
  625. # to uncopied objects. this means that if you make bart get
  626. # older via
  627. $TV{simpsons}{kids}[0]{age}++;
  628. # then this would also change in
  629. print $TV{simpsons}{members}[2]{age};
  630. # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
  631. # both point to the same underlying anonymous hash table
  632. # print the whole thing
  633. foreach $family ( keys %TV ) {
  634. print "the $family";
  635. print " is on during @{ $TV{$family}{nights} }\n";
  636. print "its members are:\n";
  637. for $who ( @{ $TV{$family}{members} } ) {
  638. print " $who->{name} ($who->{role}), age $who->{age}\n";
  639. }
  640. print "it turns out that $TV{$family}{lead} has ";
  641. print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
  642. print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
  643. print "\n";
  644. }
  645. =head1 Database Ties
  646. You cannot easily tie a multilevel data structure (such as a hash of
  647. hashes) to a dbm file. The first problem is that all but GDBM and
  648. Berkeley DB have size limitations, but beyond that, you also have problems
  649. with how references are to be represented on disk. One experimental
  650. module that does partially attempt to address this need is the MLDBM
  651. module. Check your nearest CPAN site as described in L<perlmodlib> for
  652. source code to MLDBM.
  653. =head1 SEE ALSO
  654. perlref(1), perllol(1), perldata(1), perlobj(1)
  655. =head1 AUTHOR
  656. Tom Christiansen <F<[email protected]>>
  657. Last update:
  658. Wed Oct 23 04:57:50 MET DST 1996