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