Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / man / man1 / perldsc.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLDSC 1"
132.TH PERLDSC 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134.IX Xref "data structure complex data structure struct"
135perldsc \- Perl Data Structures Cookbook
136.SH "DESCRIPTION"
137.IX Header "DESCRIPTION"
138The single feature most sorely lacking in the Perl programming language
139prior to its 5.0 release was complex data structures. Even without direct
140language support, some valiant programmers did manage to emulate them, but
141it was hard work and not for the faint of heart. You could occasionally
142get away with the \f(CW$m{$AoA,$b}\fR notation borrowed from \fBawk\fR in which the
143keys are actually more like a single concatenated string \f(CW"$AoA$b"\fR, but
144traversal and sorting were difficult. More desperate programmers even
145hacked Perl's internal symbol table directly, a strategy that proved hard
146to develop and maintain\*(--to put it mildly.
147.PP
148The 5.0 release of Perl let us have complex data structures. You
149may now write something like this and all of a sudden, you'd have an array
150with three dimensions!
151.PP
152.Vb 8
153\& for $x (1 .. 10) {
154\& for $y (1 .. 10) {
155\& for $z (1 .. 10) {
156\& $AoA[$x][$y][$z] =
157\& $x ** $y + $z;
158\& }
159\& }
160\& }
161.Ve
162.PP
163Alas, however simple this may appear, underneath it's a much more
164elaborate construct than meets the eye!
165.PP
166How do you print it out? Why can't you say just \f(CW\*(C`print @AoA\*(C'\fR? How do
167you sort it? How can you pass it to a function or get one of these back
168from a function? Is it an object? Can you save it to disk to read
169back later? How do you access whole rows or columns of that matrix? Do
170all the values have to be numeric?
171.PP
172As you see, it's quite easy to become confused. While some small portion
173of the blame for this can be attributed to the reference-based
174implementation, it's really more due to a lack of existing documentation with
175examples designed for the beginner.
176.PP
177This document is meant to be a detailed but understandable treatment of the
178many different sorts of data structures you might want to develop. It
179should also serve as a cookbook of examples. That way, when you need to
180create one of these complex data structures, you can just pinch, pilfer, or
181purloin a drop-in example from here.
182.PP
183Let's look at each of these possible constructs in detail. There are separate
184sections on each of the following:
185.IP "* arrays of arrays" 5
186.IX Item "arrays of arrays"
187.PD 0
188.IP "* hashes of arrays" 5
189.IX Item "hashes of arrays"
190.IP "* arrays of hashes" 5
191.IX Item "arrays of hashes"
192.IP "* hashes of hashes" 5
193.IX Item "hashes of hashes"
194.IP "* more elaborate constructs" 5
195.IX Item "more elaborate constructs"
196.PD
197.PP
198But for now, let's look at general issues common to all
199these types of data structures.
200.SH "REFERENCES"
201.IX Xref "reference dereference dereferencing pointer"
202.IX Header "REFERENCES"
203The most important thing to understand about all data structures in Perl
204\&\*(-- including multidimensional arrays\*(--is that even though they might
205appear otherwise, Perl \f(CW@ARRAY\fRs and \f(CW%HASH\fRes are all internally
206one\-dimensional. They can hold only scalar values (meaning a string,
207number, or a reference). They cannot directly contain other arrays or
208hashes, but instead contain \fIreferences\fR to other arrays or hashes.
209.IX Xref "multidimensional array array, multidimensional"
210.PP
211You can't use a reference to an array or hash in quite the same way that you
212would a real array or hash. For C or \*(C+ programmers unused to
213distinguishing between arrays and pointers to the same, this can be
214confusing. If so, just think of it as the difference between a structure
215and a pointer to a structure.
216.PP
217You can (and should) read more about references in the \fIperlref\fR\|(1) man
218page. Briefly, references are rather like pointers that know what they
219point to. (Objects are also a kind of reference, but we won't be needing
220them right away\*(--if ever.) This means that when you have something which
221looks to you like an access to a two-or-more-dimensional array and/or hash,
222what's really going on is that the base type is
223merely a one-dimensional entity that contains references to the next
224level. It's just that you can \fIuse\fR it as though it were a
225two-dimensional one. This is actually the way almost all C
226multidimensional arrays work as well.
227.PP
228.Vb 4
229\& $array[7][12] # array of arrays
230\& $array[7]{string} # array of hashes
231\& $hash{string}[7] # hash of arrays
232\& $hash{string}{'another string'} # hash of hashes
233.Ve
234.PP
235Now, because the top level contains only references, if you try to print
236out your array in with a simple \fIprint()\fR function, you'll get something
237that doesn't look very nice, like this:
238.PP
239.Vb 5
240\& @AoA = ( [2, 3], [4, 5, 7], [0] );
241\& print $AoA[1][2];
242\& 7
243\& print @AoA;
244\& ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
245.Ve
246.PP
247That's because Perl doesn't (ever) implicitly dereference your variables.
248If you want to get at the thing a reference is referring to, then you have
249to do this yourself using either prefix typing indicators, like
250\&\f(CW\*(C`${$blah}\*(C'\fR, \f(CW\*(C`@{$blah}\*(C'\fR, \f(CW\*(C`@{$blah[$i]}\*(C'\fR, or else postfix pointer arrows,
251like \f(CW\*(C`$a\->[3]\*(C'\fR, \f(CW\*(C`$h\->{fred}\*(C'\fR, or even \f(CW\*(C`$ob\->method()\->[3]\*(C'\fR.
252.SH "COMMON MISTAKES"
253.IX Header "COMMON MISTAKES"
254The two most common mistakes made in constructing something like
255an array of arrays is either accidentally counting the number of
256elements or else taking a reference to the same memory location
257repeatedly. Here's the case where you just get the count instead
258of a nested array:
259.PP
260.Vb 4
261\& for $i (1..10) {
262\& @array = somefunc($i);
263\& $AoA[$i] = @array; # WRONG!
264\& }
265.Ve
266.PP
267That's just the simple case of assigning an array to a scalar and getting
268its element count. If that's what you really and truly want, then you
269might do well to consider being a tad more explicit about it, like this:
270.PP
271.Vb 4
272\& for $i (1..10) {
273\& @array = somefunc($i);
274\& $counts[$i] = scalar @array;
275\& }
276.Ve
277.PP
278Here's the case of taking a reference to the same memory location
279again and again:
280.PP
281.Vb 4
282\& for $i (1..10) {
283\& @array = somefunc($i);
284\& $AoA[$i] = \e@array; # WRONG!
285\& }
286.Ve
287.PP
288So, what's the big problem with that? It looks right, doesn't it?
289After all, I just told you that you need an array of references, so by
290golly, you've made me one!
291.PP
292Unfortunately, while this is true, it's still broken. All the references
293in \f(CW@AoA\fR refer to the \fIvery same place\fR, and they will therefore all hold
294whatever was last in \f(CW@array\fR! It's similar to the problem demonstrated in
295the following C program:
296.PP
297.Vb 5
298\& #include <pwd.h>
299\& main() {
300\& struct passwd *getpwnam(), *rp, *dp;
301\& rp = getpwnam("root");
302\& dp = getpwnam("daemon");
303.Ve
304.PP
305.Vb 3
306\& printf("daemon name is %s\enroot name is %s\en",
307\& dp->pw_name, rp->pw_name);
308\& }
309.Ve
310.PP
311Which will print
312.PP
313.Vb 2
314\& daemon name is daemon
315\& root name is daemon
316.Ve
317.PP
318The problem is that both \f(CW\*(C`rp\*(C'\fR and \f(CW\*(C`dp\*(C'\fR are pointers to the same location
319in memory! In C, you'd have to remember to \fImalloc()\fR yourself some new
320memory. In Perl, you'll want to use the array constructor \f(CW\*(C`[]\*(C'\fR or the
321hash constructor \f(CW\*(C`{}\*(C'\fR instead. Here's the right way to do the preceding
322broken code fragments:
323.IX Xref "[] {}"
324.PP
325.Vb 4
326\& for $i (1..10) {
327\& @array = somefunc($i);
328\& $AoA[$i] = [ @array ];
329\& }
330.Ve
331.PP
332The square brackets make a reference to a new array with a \fIcopy\fR
333of what's in \f(CW@array\fR at the time of the assignment. This is what
334you want.
335.PP
336Note that this will produce something similar, but it's
337much harder to read:
338.PP
339.Vb 4
340\& for $i (1..10) {
341\& @array = 0 .. $i;
342\& @{$AoA[$i]} = @array;
343\& }
344.Ve
345.PP
346Is it the same? Well, maybe so\*(--and maybe not. The subtle difference
347is that when you assign something in square brackets, you know for sure
348it's always a brand new reference with a new \fIcopy\fR of the data.
349Something else could be going on in this new case with the \f(CW\*(C`@{$AoA[$i]}}\*(C'\fR
350dereference on the left-hand-side of the assignment. It all depends on
351whether \f(CW$AoA[$i]\fR had been undefined to start with, or whether it
352already contained a reference. If you had already populated \f(CW@AoA\fR with
353references, as in
354.PP
355.Vb 1
356\& $AoA[3] = \e@another_array;
357.Ve
358.PP
359Then the assignment with the indirection on the left-hand-side would
360use the existing reference that was already there:
361.PP
362.Vb 1
363\& @{$AoA[3]} = @array;
364.Ve
365.PP
366Of course, this \fIwould\fR have the \*(L"interesting\*(R" effect of clobbering
367\&\f(CW@another_array\fR. (Have you ever noticed how when a programmer says
368something is \*(L"interesting\*(R", that rather than meaning \*(L"intriguing\*(R",
369they're disturbingly more apt to mean that it's \*(L"annoying\*(R",
370\&\*(L"difficult\*(R", or both? :\-)
371.PP
372So just remember always to use the array or hash constructors with \f(CW\*(C`[]\*(C'\fR
373or \f(CW\*(C`{}\*(C'\fR, and you'll be fine, although it's not always optimally
374efficient.
375.PP
376Surprisingly, the following dangerous-looking construct will
377actually work out fine:
378.PP
379.Vb 4
380\& for $i (1..10) {
381\& my @array = somefunc($i);
382\& $AoA[$i] = \e@array;
383\& }
384.Ve
385.PP
386That's because \fImy()\fR is more of a run-time statement than it is a
387compile-time declaration \fIper se\fR. This means that the \fImy()\fR variable is
388remade afresh each time through the loop. So even though it \fIlooks\fR as
389though you stored the same variable reference each time, you actually did
390not! This is a subtle distinction that can produce more efficient code at
391the risk of misleading all but the most experienced of programmers. So I
392usually advise against teaching it to beginners. In fact, except for
393passing arguments to functions, I seldom like to see the gimme-a-reference
394operator (backslash) used much at all in code. Instead, I advise
395beginners that they (and most of the rest of us) should try to use the
396much more easily understood constructors \f(CW\*(C`[]\*(C'\fR and \f(CW\*(C`{}\*(C'\fR instead of
397relying upon lexical (or dynamic) scoping and hidden reference-counting to
398do the right thing behind the scenes.
399.PP
400In summary:
401.PP
402.Vb 3
403\& $AoA[$i] = [ @array ]; # usually best
404\& $AoA[$i] = \e@array; # perilous; just how my() was that array?
405\& @{ $AoA[$i] } = @array; # way too tricky for most programmers
406.Ve
407.SH "CAVEAT ON PRECEDENCE"
408.IX Xref "dereference, precedence dereferencing, precedence"
409.IX Header "CAVEAT ON PRECEDENCE"
410Speaking of things like \f(CW\*(C`@{$AoA[$i]}\*(C'\fR, the following are actually the
411same thing:
412.IX Xref "->"
413.PP
414.Vb 2
415\& $aref->[2][2] # clear
416\& $$aref[2][2] # confusing
417.Ve
418.PP
419That's because Perl's precedence rules on its five prefix dereferencers
420(which look like someone swearing: \f(CW\*(C`$ @ * % &\*(C'\fR) make them bind more
421tightly than the postfix subscripting brackets or braces! This will no
422doubt come as a great shock to the C or \*(C+ programmer, who is quite
423accustomed to using \f(CW*a[i]\fR to mean what's pointed to by the \fIi'th\fR
424element of \f(CW\*(C`a\*(C'\fR. That is, they first take the subscript, and only then
425dereference the thing at that subscript. That's fine in C, but this isn't C.
426.PP
427The seemingly equivalent construct in Perl, \f(CW$$aref[$i]\fR first does
428the deref of \f(CW$aref\fR, making it take \f(CW$aref\fR as a reference to an
429array, and then dereference that, and finally tell you the \fIi'th\fR value
430of the array pointed to by \f(CW$AoA\fR. If you wanted the C notion, you'd have to
431write \f(CW\*(C`${$AoA[$i]}\*(C'\fR to force the \f(CW$AoA[$i]\fR to get evaluated first
432before the leading \f(CW\*(C`$\*(C'\fR dereferencer.
433.ie n .SH "WHY YOU SHOULD ALWAYS ""use strict"""
434.el .SH "WHY YOU SHOULD ALWAYS \f(CWuse strict\fP"
435.IX Header "WHY YOU SHOULD ALWAYS use strict"
436If this is starting to sound scarier than it's worth, relax. Perl has
437some features to help you avoid its most common pitfalls. The best
438way to avoid getting confused is to start every program like this:
439.PP
440.Vb 2
441\& #!/usr/bin/perl -w
442\& use strict;
443.Ve
444.PP
445This way, you'll be forced to declare all your variables with \fImy()\fR and
446also disallow accidental \*(L"symbolic dereferencing\*(R". Therefore if you'd done
447this:
448.PP
449.Vb 5
450\& my $aref = [
451\& [ "fred", "barney", "pebbles", "bambam", "dino", ],
452\& [ "homer", "bart", "marge", "maggie", ],
453\& [ "george", "jane", "elroy", "judy", ],
454\& ];
455.Ve
456.PP
457.Vb 1
458\& print $aref[2][2];
459.Ve
460.PP
461The compiler would immediately flag that as an error \fIat compile time\fR,
462because you were accidentally accessing \f(CW@aref\fR, an undeclared
463variable, and it would thereby remind you to write instead:
464.PP
465.Vb 1
466\& print $aref->[2][2]
467.Ve
468.SH "DEBUGGING"
469.IX Xref "data structure, debugging complex data structure, debugging AoA, debugging HoA, debugging AoH, debugging HoH, debugging array of arrays, debugging hash of arrays, debugging array of hashes, debugging hash of hashes, debugging"
470.IX Header "DEBUGGING"
471Before version 5.002, the standard Perl debugger didn't do a very nice job of
472printing out complex data structures. With 5.002 or above, the
473debugger includes several new features, including command line editing as
474well as the \f(CW\*(C`x\*(C'\fR command to dump out complex data structures. For
475example, given the assignment to \f(CW$AoA\fR above, here's the debugger output:
476.PP
477.Vb 18
478\& DB<1> x $AoA
479\& $AoA = ARRAY(0x13b5a0)
480\& 0 ARRAY(0x1f0a24)
481\& 0 'fred'
482\& 1 'barney'
483\& 2 'pebbles'
484\& 3 'bambam'
485\& 4 'dino'
486\& 1 ARRAY(0x13b558)
487\& 0 'homer'
488\& 1 'bart'
489\& 2 'marge'
490\& 3 'maggie'
491\& 2 ARRAY(0x13b540)
492\& 0 'george'
493\& 1 'jane'
494\& 2 'elroy'
495\& 3 'judy'
496.Ve
497.SH "CODE EXAMPLES"
498.IX Header "CODE EXAMPLES"
499Presented with little comment (these will get their own manpages someday)
500here are short code examples illustrating access of various
501types of data structures.
502.SH "ARRAYS OF ARRAYS"
503.IX Xref "array of arrays AoA"
504.IX Header "ARRAYS OF ARRAYS"
505.Sh "Declaration of an \s-1ARRAY\s0 \s-1OF\s0 \s-1ARRAYS\s0"
506.IX Subsection "Declaration of an ARRAY OF ARRAYS"
507.Vb 5
508\& @AoA = (
509\& [ "fred", "barney" ],
510\& [ "george", "jane", "elroy" ],
511\& [ "homer", "marge", "bart" ],
512\& );
513.Ve
514.Sh "Generation of an \s-1ARRAY\s0 \s-1OF\s0 \s-1ARRAYS\s0"
515.IX Subsection "Generation of an ARRAY OF ARRAYS"
516.Vb 4
517\& # reading from file
518\& while ( <> ) {
519\& push @AoA, [ split ];
520\& }
521.Ve
522.PP
523.Vb 4
524\& # calling a function
525\& for $i ( 1 .. 10 ) {
526\& $AoA[$i] = [ somefunc($i) ];
527\& }
528.Ve
529.PP
530.Vb 5
531\& # using temp vars
532\& for $i ( 1 .. 10 ) {
533\& @tmp = somefunc($i);
534\& $AoA[$i] = [ @tmp ];
535\& }
536.Ve
537.PP
538.Vb 2
539\& # add to an existing row
540\& push @{ $AoA[0] }, "wilma", "betty";
541.Ve
542.Sh "Access and Printing of an \s-1ARRAY\s0 \s-1OF\s0 \s-1ARRAYS\s0"
543.IX Subsection "Access and Printing of an ARRAY OF ARRAYS"
544.Vb 2
545\& # one element
546\& $AoA[0][0] = "Fred";
547.Ve
548.PP
549.Vb 2
550\& # another element
551\& $AoA[1][1] =~ s/(\ew)/\eu$1/;
552.Ve
553.PP
554.Vb 4
555\& # print the whole thing with refs
556\& for $aref ( @AoA ) {
557\& print "\et [ @$aref ],\en";
558\& }
559.Ve
560.PP
561.Vb 4
562\& # print the whole thing with indices
563\& for $i ( 0 .. $#AoA ) {
564\& print "\et [ @{$AoA[$i]} ],\en";
565\& }
566.Ve
567.PP
568.Vb 6
569\& # print the whole thing one at a time
570\& for $i ( 0 .. $#AoA ) {
571\& for $j ( 0 .. $#{ $AoA[$i] } ) {
572\& print "elt $i $j is $AoA[$i][$j]\en";
573\& }
574\& }
575.Ve
576.SH "HASHES OF ARRAYS"
577.IX Xref "hash of arrays HoA"
578.IX Header "HASHES OF ARRAYS"
579.Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1ARRAYS\s0"
580.IX Subsection "Declaration of a HASH OF ARRAYS"
581.Vb 5
582\& %HoA = (
583\& flintstones => [ "fred", "barney" ],
584\& jetsons => [ "george", "jane", "elroy" ],
585\& simpsons => [ "homer", "marge", "bart" ],
586\& );
587.Ve
588.Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1ARRAYS\s0"
589.IX Subsection "Generation of a HASH OF ARRAYS"
590.Vb 6
591\& # reading from file
592\& # flintstones: fred barney wilma dino
593\& while ( <> ) {
594\& next unless s/^(.*?):\es*//;
595\& $HoA{$1} = [ split ];
596\& }
597.Ve
598.PP
599.Vb 7
600\& # reading from file; more temps
601\& # flintstones: fred barney wilma dino
602\& while ( $line = <> ) {
603\& ($who, $rest) = split /:\es*/, $line, 2;
604\& @fields = split ' ', $rest;
605\& $HoA{$who} = [ @fields ];
606\& }
607.Ve
608.PP
609.Vb 4
610\& # calling a function that returns a list
611\& for $group ( "simpsons", "jetsons", "flintstones" ) {
612\& $HoA{$group} = [ get_family($group) ];
613\& }
614.Ve
615.PP
616.Vb 5
617\& # likewise, but using temps
618\& for $group ( "simpsons", "jetsons", "flintstones" ) {
619\& @members = get_family($group);
620\& $HoA{$group} = [ @members ];
621\& }
622.Ve
623.PP
624.Vb 2
625\& # append new members to an existing family
626\& push @{ $HoA{"flintstones"} }, "wilma", "betty";
627.Ve
628.Sh "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1ARRAYS\s0"
629.IX Subsection "Access and Printing of a HASH OF ARRAYS"
630.Vb 2
631\& # one element
632\& $HoA{flintstones}[0] = "Fred";
633.Ve
634.PP
635.Vb 2
636\& # another element
637\& $HoA{simpsons}[1] =~ s/(\ew)/\eu$1/;
638.Ve
639.PP
640.Vb 4
641\& # print the whole thing
642\& foreach $family ( keys %HoA ) {
643\& print "$family: @{ $HoA{$family} }\en"
644\& }
645.Ve
646.PP
647.Vb 8
648\& # print the whole thing with indices
649\& foreach $family ( keys %HoA ) {
650\& print "family: ";
651\& foreach $i ( 0 .. $#{ $HoA{$family} } ) {
652\& print " $i = $HoA{$family}[$i]";
653\& }
654\& print "\en";
655\& }
656.Ve
657.PP
658.Vb 4
659\& # print the whole thing sorted by number of members
660\& foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
661\& print "$family: @{ $HoA{$family} }\en"
662\& }
663.Ve
664.PP
665.Vb 9
666\& # print the whole thing sorted by number of members and name
667\& foreach $family ( sort {
668\& @{$HoA{$b}} <=> @{$HoA{$a}}
669\& ||
670\& $a cmp $b
671\& } keys %HoA )
672\& {
673\& print "$family: ", join(", ", sort @{ $HoA{$family} }), "\en";
674\& }
675.Ve
676.SH "ARRAYS OF HASHES"
677.IX Xref "array of hashes AoH"
678.IX Header "ARRAYS OF HASHES"
679.Sh "Declaration of an \s-1ARRAY\s0 \s-1OF\s0 \s-1HASHES\s0"
680.IX Subsection "Declaration of an ARRAY OF HASHES"
681.Vb 16
682\& @AoH = (
683\& {
684\& Lead => "fred",
685\& Friend => "barney",
686\& },
687\& {
688\& Lead => "george",
689\& Wife => "jane",
690\& Son => "elroy",
691\& },
692\& {
693\& Lead => "homer",
694\& Wife => "marge",
695\& Son => "bart",
696\& }
697\& );
698.Ve
699.Sh "Generation of an \s-1ARRAY\s0 \s-1OF\s0 \s-1HASHES\s0"
700.IX Subsection "Generation of an ARRAY OF HASHES"
701.Vb 10
702\& # reading from file
703\& # format: LEAD=fred FRIEND=barney
704\& while ( <> ) {
705\& $rec = {};
706\& for $field ( split ) {
707\& ($key, $value) = split /=/, $field;
708\& $rec->{$key} = $value;
709\& }
710\& push @AoH, $rec;
711\& }
712.Ve
713.PP
714.Vb 6
715\& # reading from file
716\& # format: LEAD=fred FRIEND=barney
717\& # no temp
718\& while ( <> ) {
719\& push @AoH, { split /[\es+=]/ };
720\& }
721.Ve
722.PP
723.Vb 5
724\& # calling a function that returns a key/value pair list, like
725\& # "lead","fred","daughter","pebbles"
726\& while ( %fields = getnextpairset() ) {
727\& push @AoH, { %fields };
728\& }
729.Ve
730.PP
731.Vb 4
732\& # likewise, but using no temp vars
733\& while (<>) {
734\& push @AoH, { parsepairs($_) };
735\& }
736.Ve
737.PP
738.Vb 3
739\& # add key/value to an element
740\& $AoH[0]{pet} = "dino";
741\& $AoH[2]{pet} = "santa's little helper";
742.Ve
743.Sh "Access and Printing of an \s-1ARRAY\s0 \s-1OF\s0 \s-1HASHES\s0"
744.IX Subsection "Access and Printing of an ARRAY OF HASHES"
745.Vb 2
746\& # one element
747\& $AoH[0]{lead} = "fred";
748.Ve
749.PP
750.Vb 2
751\& # another element
752\& $AoH[1]{lead} =~ s/(\ew)/\eu$1/;
753.Ve
754.PP
755.Vb 8
756\& # print the whole thing with refs
757\& for $href ( @AoH ) {
758\& print "{ ";
759\& for $role ( keys %$href ) {
760\& print "$role=$href->{$role} ";
761\& }
762\& print "}\en";
763\& }
764.Ve
765.PP
766.Vb 8
767\& # print the whole thing with indices
768\& for $i ( 0 .. $#AoH ) {
769\& print "$i is { ";
770\& for $role ( keys %{ $AoH[$i] } ) {
771\& print "$role=$AoH[$i]{$role} ";
772\& }
773\& print "}\en";
774\& }
775.Ve
776.PP
777.Vb 6
778\& # print the whole thing one at a time
779\& for $i ( 0 .. $#AoH ) {
780\& for $role ( keys %{ $AoH[$i] } ) {
781\& print "elt $i $role is $AoH[$i]{$role}\en";
782\& }
783\& }
784.Ve
785.SH "HASHES OF HASHES"
786.IX Xref "hass of hashes HoH"
787.IX Header "HASHES OF HASHES"
788.Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0"
789.IX Subsection "Declaration of a HASH OF HASHES"
790.Vb 16
791\& %HoH = (
792\& flintstones => {
793\& lead => "fred",
794\& pal => "barney",
795\& },
796\& jetsons => {
797\& lead => "george",
798\& wife => "jane",
799\& "his boy" => "elroy",
800\& },
801\& simpsons => {
802\& lead => "homer",
803\& wife => "marge",
804\& kid => "bart",
805\& },
806\& );
807.Ve
808.Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0"
809.IX Subsection "Generation of a HASH OF HASHES"
810.Vb 9
811\& # reading from file
812\& # flintstones: lead=fred pal=barney wife=wilma pet=dino
813\& while ( <> ) {
814\& next unless s/^(.*?):\es*//;
815\& $who = $1;
816\& for $field ( split ) {
817\& ($key, $value) = split /=/, $field;
818\& $HoH{$who}{$key} = $value;
819\& }
820.Ve
821.PP
822.Vb 11
823\& # reading from file; more temps
824\& while ( <> ) {
825\& next unless s/^(.*?):\es*//;
826\& $who = $1;
827\& $rec = {};
828\& $HoH{$who} = $rec;
829\& for $field ( split ) {
830\& ($key, $value) = split /=/, $field;
831\& $rec->{$key} = $value;
832\& }
833\& }
834.Ve
835.PP
836.Vb 4
837\& # calling a function that returns a key,value hash
838\& for $group ( "simpsons", "jetsons", "flintstones" ) {
839\& $HoH{$group} = { get_family($group) };
840\& }
841.Ve
842.PP
843.Vb 5
844\& # likewise, but using temps
845\& for $group ( "simpsons", "jetsons", "flintstones" ) {
846\& %members = get_family($group);
847\& $HoH{$group} = { %members };
848\& }
849.Ve
850.PP
851.Vb 5
852\& # append new members to an existing family
853\& %new_folks = (
854\& wife => "wilma",
855\& pet => "dino",
856\& );
857.Ve
858.PP
859.Vb 3
860\& for $what (keys %new_folks) {
861\& $HoH{flintstones}{$what} = $new_folks{$what};
862\& }
863.Ve
864.Sh "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0"
865.IX Subsection "Access and Printing of a HASH OF HASHES"
866.Vb 2
867\& # one element
868\& $HoH{flintstones}{wife} = "wilma";
869.Ve
870.PP
871.Vb 2
872\& # another element
873\& $HoH{simpsons}{lead} =~ s/(\ew)/\eu$1/;
874.Ve
875.PP
876.Vb 8
877\& # print the whole thing
878\& foreach $family ( keys %HoH ) {
879\& print "$family: { ";
880\& for $role ( keys %{ $HoH{$family} } ) {
881\& print "$role=$HoH{$family}{$role} ";
882\& }
883\& print "}\en";
884\& }
885.Ve
886.PP
887.Vb 8
888\& # print the whole thing somewhat sorted
889\& foreach $family ( sort keys %HoH ) {
890\& print "$family: { ";
891\& for $role ( sort keys %{ $HoH{$family} } ) {
892\& print "$role=$HoH{$family}{$role} ";
893\& }
894\& print "}\en";
895\& }
896.Ve
897.PP
898.Vb 8
899\& # print the whole thing sorted by number of members
900\& foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) {
901\& print "$family: { ";
902\& for $role ( sort keys %{ $HoH{$family} } ) {
903\& print "$role=$HoH{$family}{$role} ";
904\& }
905\& print "}\en";
906\& }
907.Ve
908.PP
909.Vb 3
910\& # establish a sort order (rank) for each role
911\& $i = 0;
912\& for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
913.Ve
914.PP
915.Vb 9
916\& # now print the whole thing sorted by number of members
917\& foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) {
918\& print "$family: { ";
919\& # and print these according to rank order
920\& for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) {
921\& print "$role=$HoH{$family}{$role} ";
922\& }
923\& print "}\en";
924\& }
925.Ve
926.SH "MORE ELABORATE RECORDS"
927.IX Xref "record structure struct"
928.IX Header "MORE ELABORATE RECORDS"
929.Sh "Declaration of \s-1MORE\s0 \s-1ELABORATE\s0 \s-1RECORDS\s0"
930.IX Subsection "Declaration of MORE ELABORATE RECORDS"
931Here's a sample showing how to create and use a record whose fields are of
932many different sorts:
933.PP
934.Vb 8
935\& $rec = {
936\& TEXT => $string,
937\& SEQUENCE => [ @old_values ],
938\& LOOKUP => { %some_table },
939\& THATCODE => \e&some_function,
940\& THISCODE => sub { $_[0] ** $_[1] },
941\& HANDLE => \e*STDOUT,
942\& };
943.Ve
944.PP
945.Vb 1
946\& print $rec->{TEXT};
947.Ve
948.PP
949.Vb 2
950\& print $rec->{SEQUENCE}[0];
951\& $last = pop @ { $rec->{SEQUENCE} };
952.Ve
953.PP
954.Vb 2
955\& print $rec->{LOOKUP}{"key"};
956\& ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
957.Ve
958.PP
959.Vb 2
960\& $answer = $rec->{THATCODE}->($arg);
961\& $answer = $rec->{THISCODE}->($arg1, $arg2);
962.Ve
963.PP
964.Vb 2
965\& # careful of extra block braces on fh ref
966\& print { $rec->{HANDLE} } "a string\en";
967.Ve
968.PP
969.Vb 3
970\& use FileHandle;
971\& $rec->{HANDLE}->autoflush(1);
972\& $rec->{HANDLE}->print(" a string\en");
973.Ve
974.Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0"
975.IX Subsection "Declaration of a HASH OF COMPLEX RECORDS"
976.Vb 10
977\& %TV = (
978\& flintstones => {
979\& series => "flintstones",
980\& nights => [ qw(monday thursday friday) ],
981\& members => [
982\& { name => "fred", role => "lead", age => 36, },
983\& { name => "wilma", role => "wife", age => 31, },
984\& { name => "pebbles", role => "kid", age => 4, },
985\& ],
986\& },
987.Ve
988.PP
989.Vb 9
990\& jetsons => {
991\& series => "jetsons",
992\& nights => [ qw(wednesday saturday) ],
993\& members => [
994\& { name => "george", role => "lead", age => 41, },
995\& { name => "jane", role => "wife", age => 39, },
996\& { name => "elroy", role => "kid", age => 9, },
997\& ],
998\& },
999.Ve
1000.PP
1001.Vb 10
1002\& simpsons => {
1003\& series => "simpsons",
1004\& nights => [ qw(monday) ],
1005\& members => [
1006\& { name => "homer", role => "lead", age => 34, },
1007\& { name => "marge", role => "wife", age => 37, },
1008\& { name => "bart", role => "kid", age => 11, },
1009\& ],
1010\& },
1011\& );
1012.Ve
1013.Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0"
1014.IX Subsection "Generation of a HASH OF COMPLEX RECORDS"
1015.Vb 5
1016\& # reading from file
1017\& # this is most easily done by having the file itself be
1018\& # in the raw data format as shown above. perl is happy
1019\& # to parse complex data structures if declared as data, so
1020\& # sometimes it's easiest to do that
1021.Ve
1022.PP
1023.Vb 4
1024\& # here's a piece by piece build up
1025\& $rec = {};
1026\& $rec->{series} = "flintstones";
1027\& $rec->{nights} = [ find_days() ];
1028.Ve
1029.PP
1030.Vb 7
1031\& @members = ();
1032\& # assume this file in field=value syntax
1033\& while (<>) {
1034\& %fields = split /[\es=]+/;
1035\& push @members, { %fields };
1036\& }
1037\& $rec->{members} = [ @members ];
1038.Ve
1039.PP
1040.Vb 2
1041\& # now remember the whole thing
1042\& $TV{ $rec->{series} } = $rec;
1043.Ve
1044.PP
1045.Vb 19
1046\& ###########################################################
1047\& # now, you might want to make interesting extra fields that
1048\& # include pointers back into the same data structure so if
1049\& # change one piece, it changes everywhere, like for example
1050\& # if you wanted a {kids} field that was a reference
1051\& # to an array of the kids' records without having duplicate
1052\& # records and thus update problems.
1053\& ###########################################################
1054\& foreach $family (keys %TV) {
1055\& $rec = $TV{$family}; # temp pointer
1056\& @kids = ();
1057\& for $person ( @{ $rec->{members} } ) {
1058\& if ($person->{role} =~ /kid|son|daughter/) {
1059\& push @kids, $person;
1060\& }
1061\& }
1062\& # REMEMBER: $rec and $TV{$family} point to same data!!
1063\& $rec->{kids} = [ @kids ];
1064\& }
1065.Ve
1066.PP
1067.Vb 3
1068\& # you copied the array, but the array itself contains pointers
1069\& # to uncopied objects. this means that if you make bart get
1070\& # older via
1071.Ve
1072.PP
1073.Vb 1
1074\& $TV{simpsons}{kids}[0]{age}++;
1075.Ve
1076.PP
1077.Vb 2
1078\& # then this would also change in
1079\& print $TV{simpsons}{members}[2]{age};
1080.Ve
1081.PP
1082.Vb 2
1083\& # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
1084\& # both point to the same underlying anonymous hash table
1085.Ve
1086.PP
1087.Vb 13
1088\& # print the whole thing
1089\& foreach $family ( keys %TV ) {
1090\& print "the $family";
1091\& print " is on during @{ $TV{$family}{nights} }\en";
1092\& print "its members are:\en";
1093\& for $who ( @{ $TV{$family}{members} } ) {
1094\& print " $who->{name} ($who->{role}), age $who->{age}\en";
1095\& }
1096\& print "it turns out that $TV{$family}{lead} has ";
1097\& print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
1098\& print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
1099\& print "\en";
1100\& }
1101.Ve
1102.SH "Database Ties"
1103.IX Header "Database Ties"
1104You cannot easily tie a multilevel data structure (such as a hash of
1105hashes) to a dbm file. The first problem is that all but \s-1GDBM\s0 and
1106Berkeley \s-1DB\s0 have size limitations, but beyond that, you also have problems
1107with how references are to be represented on disk. One experimental
1108module that does partially attempt to address this need is the \s-1MLDBM\s0
1109module. Check your nearest \s-1CPAN\s0 site as described in perlmodlib for
1110source code to \s-1MLDBM\s0.
1111.SH "SEE ALSO"
1112.IX Header "SEE ALSO"
1113\&\fIperlref\fR\|(1), \fIperllol\fR\|(1), \fIperldata\fR\|(1), \fIperlobj\fR\|(1)
1114.SH "AUTHOR"
1115.IX Header "AUTHOR"
1116Tom Christiansen <\fItchrist@perl.com\fR>
1117.PP
1118Last update:
1119Wed Oct 23 04:57:50 \s-1MET\s0 \s-1DST\s0 1996