CINXE.COM
perldsc - Perl Data Structures Cookbook - Perldoc Browser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>perldsc - Perl Data Structures Cookbook - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perldsc"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/">Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.16.2</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perldsc">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0/perldsc">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.2/perldsc">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perldsc">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perldsc">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perldsc">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perldsc">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perldsc">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perldsc">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perldsc">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perldsc">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perldsc">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perldsc">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perldsc">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perldsc">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perldsc">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perldsc">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perldsc">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perldsc">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perldsc">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perldsc">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perldsc">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perldsc">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perldsc">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perldsc">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perldsc">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perldsc">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perldsc">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perldsc">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perldsc">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perldsc">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perldsc">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perldsc">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perldsc">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perldsc">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perldsc">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perldsc">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perldsc">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perldsc">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perldsc">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perldsc">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perldsc">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perldsc">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perldsc">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perldsc">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perldsc">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perldsc">5.16.3</a> <a class="dropdown-item active" href="/5.16.2/perldsc">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perldsc">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perldsc">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perldsc">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perldsc">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perldsc">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perldsc">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perldsc">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perldsc">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perldsc">5.12.4</a> <a class="dropdown-item" href="/5.12.3/perldsc">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perldsc">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perldsc">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perldsc">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perldsc">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perldsc">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perldsc">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perldsc">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perldsc">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perldsc">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perldsc">5.8.5</a> <a class="dropdown-item" href="/5.8.4/perldsc">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perldsc">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perldsc">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perldsc">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perldsc">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perldsc">5.6.2</a> <a class="dropdown-item" href="/5.6.1/perldsc">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perldsc">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perldsc">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perldsc">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perldsc">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perldsc">5.005_01</a> <a class="dropdown-item" href="/5.005/perldsc">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item" href="/blead/perldsc">blead</a> <a class="dropdown-item" href="/5.41.6/perldsc">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perldsc">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perldsc">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perldsc">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perldsc">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perldsc">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0-RC2/perldsc">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perldsc">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perldsc">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perldsc">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perldsc">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perldsc">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perldsc">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perldsc">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perldsc">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perldsc">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perldsc">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perldsc">5.39.1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/5.16.2/perl">Perl</a> <a class="dropdown-item" href="/5.16.2/perlintro">Intro</a> <a class="dropdown-item" href="/5.16.2/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.16.2/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.16.2/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.2/perlop">Operators</a> <a class="dropdown-item" href="/5.16.2/functions">Functions</a> <a class="dropdown-item" href="/5.16.2/variables">Variables</a> <a class="dropdown-item" href="/5.16.2/modules">Modules</a> <a class="dropdown-item" href="/5.16.2/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.2/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.16.2/perlcommunity">Community</a> <a class="dropdown-item" href="/5.16.2/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/5.16.2/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/5.16.2/perldsc">perldsc</a> <div id="more"> (<a href="/5.16.2/perldsc.txt">source</a>, <a href="https://metacpan.org/pod/perldsc">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.16.2. <a href="/perldsc">View the latest version</a> </div> <h1><a id="toc">CONTENTS</a></h1> <ul> <li> <a class="text-decoration-none" href="#NAME">NAME </a> </li> <li> <a class="text-decoration-none" href="#DESCRIPTION">DESCRIPTION</a> </li> <li> <a class="text-decoration-none" href="#REFERENCES">REFERENCES </a> </li> <li> <a class="text-decoration-none" href="#COMMON-MISTAKES">COMMON MISTAKES</a> </li> <li> <a class="text-decoration-none" href="#CAVEAT-ON-PRECEDENCE">CAVEAT ON PRECEDENCE </a> </li> <li> <a class="text-decoration-none" href="#WHY-YOU-SHOULD-ALWAYS-use-strict">WHY YOU SHOULD ALWAYS use strict</a> </li> <li> <a class="text-decoration-none" href="#DEBUGGING">DEBUGGING </a> </li> <li> <a class="text-decoration-none" href="#CODE-EXAMPLES">CODE EXAMPLES</a> </li> <li> <a class="text-decoration-none" href="#ARRAYS-OF-ARRAYS">ARRAYS OF ARRAYS </a> <ul> <li> <a class="text-decoration-none" href="#Declaration-of-an-ARRAY-OF-ARRAYS">Declaration of an ARRAY OF ARRAYS</a> </li> <li> <a class="text-decoration-none" href="#Generation-of-an-ARRAY-OF-ARRAYS">Generation of an ARRAY OF ARRAYS</a> </li> <li> <a class="text-decoration-none" href="#Access-and-Printing-of-an-ARRAY-OF-ARRAYS">Access and Printing of an ARRAY OF ARRAYS</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#HASHES-OF-ARRAYS">HASHES OF ARRAYS </a> <ul> <li> <a class="text-decoration-none" href="#Declaration-of-a-HASH-OF-ARRAYS">Declaration of a HASH OF ARRAYS</a> </li> <li> <a class="text-decoration-none" href="#Generation-of-a-HASH-OF-ARRAYS">Generation of a HASH OF ARRAYS</a> </li> <li> <a class="text-decoration-none" href="#Access-and-Printing-of-a-HASH-OF-ARRAYS">Access and Printing of a HASH OF ARRAYS</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#ARRAYS-OF-HASHES">ARRAYS OF HASHES </a> <ul> <li> <a class="text-decoration-none" href="#Declaration-of-an-ARRAY-OF-HASHES">Declaration of an ARRAY OF HASHES</a> </li> <li> <a class="text-decoration-none" href="#Generation-of-an-ARRAY-OF-HASHES">Generation of an ARRAY OF HASHES</a> </li> <li> <a class="text-decoration-none" href="#Access-and-Printing-of-an-ARRAY-OF-HASHES">Access and Printing of an ARRAY OF HASHES</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#HASHES-OF-HASHES">HASHES OF HASHES </a> <ul> <li> <a class="text-decoration-none" href="#Declaration-of-a-HASH-OF-HASHES">Declaration of a HASH OF HASHES</a> </li> <li> <a class="text-decoration-none" href="#Generation-of-a-HASH-OF-HASHES">Generation of a HASH OF HASHES</a> </li> <li> <a class="text-decoration-none" href="#Access-and-Printing-of-a-HASH-OF-HASHES">Access and Printing of a HASH OF HASHES</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#MORE-ELABORATE-RECORDS">MORE ELABORATE RECORDS </a> <ul> <li> <a class="text-decoration-none" href="#Declaration-of-MORE-ELABORATE-RECORDS">Declaration of MORE ELABORATE RECORDS</a> </li> <li> <a class="text-decoration-none" href="#Declaration-of-a-HASH-OF-COMPLEX-RECORDS">Declaration of a HASH OF COMPLEX RECORDS</a> </li> <li> <a class="text-decoration-none" href="#Generation-of-a-HASH-OF-COMPLEX-RECORDS">Generation of a HASH OF COMPLEX RECORDS</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Database-Ties">Database Ties</a> </li> <li> <a class="text-decoration-none" href="#SEE-ALSO">SEE ALSO</a> </li> <li> <a class="text-decoration-none" href="#AUTHOR">AUTHOR</a> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME </h1> <p>perldsc - Perl Data Structures Cookbook</p> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>The single feature most sorely lacking in the Perl programming language prior to its 5.0 release was complex data structures. Even without direct language support, some valiant programmers did manage to emulate them, but it was hard work and not for the faint of heart. You could occasionally get away with the <code>$m{$AoA,$b}</code> notation borrowed from <b>awk</b> in which the keys are actually more like a single concatenated string <code>"$AoA$b"</code>, but traversal and sorting were difficult. More desperate programmers even hacked Perl's internal symbol table directly, a strategy that proved hard to develop and maintain--to put it mildly.</p> <p>The 5.0 release of Perl let us have complex data structures. You may now write something like this and all of a sudden, you'd have an array with three dimensions!</p> <pre><code> for $x (1 .. 10) { for $y (1 .. 10) { for $z (1 .. 10) { $AoA[$x][$y][$z] = $x ** $y + $z; } } }</code></pre> <p>Alas, however simple this may appear, underneath it's a much more elaborate construct than meets the eye!</p> <p>How do you print it out? Why can't you say just <code>print @AoA</code>? 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?</p> <p>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.</p> <p>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.</p> <p>Let's look at each of these possible constructs in detail. There are separate sections on each of the following:</p> <ul> <li><p>arrays of arrays</p> </li> <li><p>hashes of arrays</p> </li> <li><p>arrays of hashes</p> </li> <li><p>hashes of hashes</p> </li> <li><p>more elaborate constructs</p> </li> </ul> <p>But for now, let's look at general issues common to all these types of data structures.</p> <h1 id="REFERENCES"><a class="permalink" href="#REFERENCES">#</a>REFERENCES </h1> <p>The most important thing to understand about all data structures in Perl--including multidimensional arrays--is that even though they might appear otherwise, Perl <code>@ARRAY</code>s and <code>%HASH</code>es 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 <i>references</i> to other arrays or hashes. </p> <p>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.</p> <p>You can (and should) read more about references in <a href="/5.16.2/perlref">perlref</a>. 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 <i>use</i> it as though it were a two-dimensional one. This is actually the way almost all C multidimensional arrays work as well.</p> <pre><code>$array[7][12] # array of arrays $array[7]{string} # array of hashes $hash{string}[7] # hash of arrays $hash{string}{'another string'} # hash of hashes</code></pre> <p>Now, because the top level contains only references, if you try to print out your array in with a simple print() function, you'll get something that doesn't look very nice, like this:</p> <pre><code> @AoA = ( [2, 3], [4, 5, 7], [0] ); print $AoA[1][2]; 7 print @AoA; ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)</code></pre> <p>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 <code>${$blah}</code>, <code>@{$blah}</code>, <code>@{$blah[$i]}</code>, or else postfix pointer arrows, like <code>$a->[3]</code>, <code>$h->{fred}</code>, or even <code>$ob->method()->[3]</code>.</p> <h1 id="COMMON-MISTAKES"><a class="permalink" href="#COMMON-MISTAKES">#</a><a id="COMMON"></a>COMMON MISTAKES</h1> <p>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:</p> <pre><code> for $i (1..10) { @array = somefunc($i); $AoA[$i] = @array; # WRONG! }</code></pre> <p>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:</p> <pre><code> for $i (1..10) { @array = somefunc($i); $counts[$i] = scalar @array; }</code></pre> <p>Here's the case of taking a reference to the same memory location again and again:</p> <pre><code> for $i (1..10) { @array = somefunc($i); $AoA[$i] = \@array; # WRONG! }</code></pre> <p>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!</p> <p>Unfortunately, while this is true, it's still broken. All the references in @AoA refer to the <i>very same place</i>, and they will therefore all hold whatever was last in @array! It's similar to the problem demonstrated in the following C program:</p> <pre><code> #include <pwd.h> main() { struct passwd *getpwnam(), *rp, *dp; rp = getpwnam("root"); dp = getpwnam("daemon"); printf("daemon name is %s\nroot name is %s\n", dp->pw_name, rp->pw_name); }</code></pre> <p>Which will print</p> <pre><code class="plaintext">daemon name is daemon root name is daemon</code></pre> <p>The problem is that both <code>rp</code> and <code>dp</code> are pointers to the same location in memory! In C, you'd have to remember to malloc() yourself some new memory. In Perl, you'll want to use the array constructor <code>[]</code> or the hash constructor <code>{}</code> instead. Here's the right way to do the preceding broken code fragments: </p> <pre><code> for $i (1..10) { @array = somefunc($i); $AoA[$i] = [ @array ]; }</code></pre> <p>The square brackets make a reference to a new array with a <i>copy</i> of what's in @array at the time of the assignment. This is what you want.</p> <p>Note that this will produce something similar, but it's much harder to read:</p> <pre><code> for $i (1..10) { @array = 0 .. $i; @{$AoA[$i]} = @array; }</code></pre> <p>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 <i>copy</i> of the data. Something else could be going on in this new case with the <code>@{$AoA[$i]}</code> dereference on the left-hand-side of the assignment. It all depends on whether <code>$AoA[$i]</code> had been undefined to start with, or whether it already contained a reference. If you had already populated @AoA with references, as in</p> <pre><code>$AoA[3] = \@another_array;</code></pre> <p>Then the assignment with the indirection on the left-hand-side would use the existing reference that was already there:</p> <pre><code>@{$AoA[3]} = @array;</code></pre> <p>Of course, this <i>would</i> have the "interesting" effect of clobbering @another_array. (Have you ever noticed how when a programmer says something is "interesting", that rather than meaning "intriguing", they're disturbingly more apt to mean that it's "annoying", "difficult", or both? :-)</p> <p>So just remember always to use the array or hash constructors with <code>[]</code> or <code>{}</code>, and you'll be fine, although it's not always optimally efficient.</p> <p>Surprisingly, the following dangerous-looking construct will actually work out fine:</p> <pre><code>for $i (1..10) { my @array = somefunc($i); $AoA[$i] = \@array; }</code></pre> <p>That's because my() is more of a run-time statement than it is a compile-time declaration <i>per se</i>. This means that the my() variable is remade afresh each time through the loop. So even though it <i>looks</i> 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 <code>[]</code> and <code>{}</code> instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes.</p> <p>In summary:</p> <pre><code>$AoA[$i] = [ @array ]; # usually best $AoA[$i] = \@array; # perilous; just how my() was that array? @{ $AoA[$i] } = @array; # way too tricky for most programmers</code></pre> <h1 id="CAVEAT-ON-PRECEDENCE"><a class="permalink" href="#CAVEAT-ON-PRECEDENCE">#</a><a id="CAVEAT"></a>CAVEAT ON PRECEDENCE </h1> <p>Speaking of things like <code>@{$AoA[$i]}</code>, the following are actually the same thing: </p> <pre><code>$aref->[2][2] # clear $$aref[2][2] # confusing</code></pre> <p>That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: <code>$ @ * % &</code>) 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 <code>*a[i]</code> to mean what's pointed to by the <i>i'th</i> element of <code>a</code>. 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.</p> <p>The seemingly equivalent construct in Perl, <code>$$aref[$i]</code> first does the deref of $aref, making it take $aref as a reference to an array, and then dereference that, and finally tell you the <i>i'th</i> value of the array pointed to by $AoA. If you wanted the C notion, you'd have to write <code>${$AoA[$i]}</code> to force the <code>$AoA[$i]</code> to get evaluated first before the leading <code>$</code> dereferencer.</p> <h1 id="WHY-YOU-SHOULD-ALWAYS-use-strict"><a class="permalink" href="#WHY-YOU-SHOULD-ALWAYS-use-strict">#</a><a id="WHY"></a>WHY YOU SHOULD ALWAYS <code>use strict</code></h1> <p>If this is starting to sound scarier than it's worth, relax. Perl has some features to help you avoid its most common pitfalls. The best way to avoid getting confused is to start every program like this:</p> <pre><code>#!/usr/bin/perl -w use strict;</code></pre> <p>This way, you'll be forced to declare all your variables with my() and also disallow accidental "symbolic dereferencing". Therefore if you'd done this:</p> <pre><code> my $aref = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "homer", "bart", "marge", "maggie", ], [ "george", "jane", "elroy", "judy", ], ]; print $aref[2][2];</code></pre> <p>The compiler would immediately flag that as an error <i>at compile time</i>, because you were accidentally accessing <code>@aref</code>, an undeclared variable, and it would thereby remind you to write instead:</p> <pre><code>print $aref->[2][2]</code></pre> <h1 id="DEBUGGING"><a class="permalink" href="#DEBUGGING">#</a>DEBUGGING </h1> <p>Before version 5.002, the standard Perl debugger didn't do a very nice job of printing out complex data structures. With 5.002 or above, the debugger includes several new features, including command line editing as well as the <code>x</code> command to dump out complex data structures. For example, given the assignment to $AoA above, here's the debugger output:</p> <pre><code> DB<1> x $AoA $AoA = ARRAY(0x13b5a0) 0 ARRAY(0x1f0a24) 0 'fred' 1 'barney' 2 'pebbles' 3 'bambam' 4 'dino' 1 ARRAY(0x13b558) 0 'homer' 1 'bart' 2 'marge' 3 'maggie' 2 ARRAY(0x13b540) 0 'george' 1 'jane' 2 'elroy' 3 'judy'</code></pre> <h1 id="CODE-EXAMPLES"><a class="permalink" href="#CODE-EXAMPLES">#</a><a id="CODE"></a>CODE EXAMPLES</h1> <p>Presented with little comment (these will get their own manpages someday) here are short code examples illustrating access of various types of data structures.</p> <h1 id="ARRAYS-OF-ARRAYS"><a class="permalink" href="#ARRAYS-OF-ARRAYS">#</a><a id="ARRAYS"></a>ARRAYS OF ARRAYS </h1> <h2 id="Declaration-of-an-ARRAY-OF-ARRAYS"><a class="permalink" href="#Declaration-of-an-ARRAY-OF-ARRAYS">#</a><a id="Declaration"></a>Declaration of an ARRAY OF ARRAYS</h2> <pre><code>@AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], );</code></pre> <h2 id="Generation-of-an-ARRAY-OF-ARRAYS"><a class="permalink" href="#Generation-of-an-ARRAY-OF-ARRAYS">#</a><a id="Generation"></a>Generation of an ARRAY OF ARRAYS</h2> <pre><code># reading from file while ( <> ) { push @AoA, [ split ]; } # calling a function for $i ( 1 .. 10 ) { $AoA[$i] = [ somefunc($i) ]; } # using temp vars for $i ( 1 .. 10 ) { @tmp = somefunc($i); $AoA[$i] = [ @tmp ]; } # add to an existing row push @{ $AoA[0] }, "wilma", "betty";</code></pre> <h2 id="Access-and-Printing-of-an-ARRAY-OF-ARRAYS"><a class="permalink" href="#Access-and-Printing-of-an-ARRAY-OF-ARRAYS">#</a><a id="Access"></a>Access and Printing of an ARRAY OF ARRAYS</h2> <pre><code># one element $AoA[0][0] = "Fred"; # another element $AoA[1][1] =~ s/(\w)/\u$1/; # print the whole thing with refs for $aref ( @AoA ) { print "\t [ @$aref ],\n"; } # print the whole thing with indices for $i ( 0 .. $#AoA ) { print "\t [ @{$AoA[$i]} ],\n"; } # print the whole thing one at a time for $i ( 0 .. $#AoA ) { for $j ( 0 .. $#{ $AoA[$i] } ) { print "elt $i $j is $AoA[$i][$j]\n"; } }</code></pre> <h1 id="HASHES-OF-ARRAYS"><a class="permalink" href="#HASHES-OF-ARRAYS">#</a><a id="HASHES"></a>HASHES OF ARRAYS </h1> <h2 id="Declaration-of-a-HASH-OF-ARRAYS"><a class="permalink" href="#Declaration-of-a-HASH-OF-ARRAYS">#</a><a id="Declaration1"></a>Declaration of a HASH OF ARRAYS</h2> <pre><code>%HoA = ( flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy" ], simpsons => [ "homer", "marge", "bart" ], );</code></pre> <h2 id="Generation-of-a-HASH-OF-ARRAYS"><a class="permalink" href="#Generation-of-a-HASH-OF-ARRAYS">#</a><a id="Generation1"></a>Generation of a HASH OF ARRAYS</h2> <pre><code># reading from file # flintstones: fred barney wilma dino while ( <> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split ]; } # reading from file; more temps # flintstones: fred barney wilma dino while ( $line = <> ) { ($who, $rest) = split /:\s*/, $line, 2; @fields = split ' ', $rest; $HoA{$who} = [ @fields ]; } # calling a function that returns a list for $group ( "simpsons", "jetsons", "flintstones" ) { $HoA{$group} = [ get_family($group) ]; } # likewise, but using temps for $group ( "simpsons", "jetsons", "flintstones" ) { @members = get_family($group); $HoA{$group} = [ @members ]; } # append new members to an existing family push @{ $HoA{"flintstones"} }, "wilma", "betty";</code></pre> <h2 id="Access-and-Printing-of-a-HASH-OF-ARRAYS"><a class="permalink" href="#Access-and-Printing-of-a-HASH-OF-ARRAYS">#</a><a id="Access1"></a>Access and Printing of a HASH OF ARRAYS</h2> <pre><code> # one element $HoA{flintstones}[0] = "Fred"; # another element $HoA{simpsons}[1] =~ s/(\w)/\u$1/; # print the whole thing foreach $family ( keys %HoA ) { print "$family: @{ $HoA{$family} }\n" } # print the whole thing with indices foreach $family ( keys %HoA ) { print "family: "; foreach $i ( 0 .. $#{ $HoA{$family} } ) { print " $i = $HoA{$family}[$i]"; } print "\n"; } # print the whole thing sorted by number of members foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) { print "$family: @{ $HoA{$family} }\n" } # print the whole thing sorted by number of members and name foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} || $a cmp $b } keys %HoA ) { print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n"; }</code></pre> <h1 id="ARRAYS-OF-HASHES"><a class="permalink" href="#ARRAYS-OF-HASHES">#</a><a id="ARRAYS1"></a>ARRAYS OF HASHES </h1> <h2 id="Declaration-of-an-ARRAY-OF-HASHES"><a class="permalink" href="#Declaration-of-an-ARRAY-OF-HASHES">#</a><a id="Declaration2"></a>Declaration of an ARRAY OF HASHES</h2> <pre><code>@AoH = ( { Lead => "fred", Friend => "barney", }, { Lead => "george", Wife => "jane", Son => "elroy", }, { Lead => "homer", Wife => "marge", Son => "bart", } );</code></pre> <h2 id="Generation-of-an-ARRAY-OF-HASHES"><a class="permalink" href="#Generation-of-an-ARRAY-OF-HASHES">#</a><a id="Generation2"></a>Generation of an ARRAY OF HASHES</h2> <pre><code># reading from file # format: LEAD=fred FRIEND=barney while ( <> ) { $rec = {}; for $field ( split ) { ($key, $value) = split /=/, $field; $rec->{$key} = $value; } push @AoH, $rec; } # reading from file # format: LEAD=fred FRIEND=barney # no temp while ( <> ) { push @AoH, { split /[\s+=]/ }; } # calling a function that returns a key/value pair list, like # "lead","fred","daughter","pebbles" while ( %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's little helper";</code></pre> <h2 id="Access-and-Printing-of-an-ARRAY-OF-HASHES"><a class="permalink" href="#Access-and-Printing-of-an-ARRAY-OF-HASHES">#</a><a id="Access2"></a>Access and Printing of an ARRAY OF HASHES</h2> <pre><code># one element $AoH[0]{lead} = "fred"; # another element $AoH[1]{lead} =~ s/(\w)/\u$1/; # print the whole thing with refs for $href ( @AoH ) { print "{ "; for $role ( keys %$href ) { print "$role=$href->{$role} "; } print "}\n"; } # print the whole thing with indices for $i ( 0 .. $#AoH ) { print "$i is { "; for $role ( keys %{ $AoH[$i] } ) { print "$role=$AoH[$i]{$role} "; } print "}\n"; } # print the whole thing one at a time for $i ( 0 .. $#AoH ) { for $role ( keys %{ $AoH[$i] } ) { print "elt $i $role is $AoH[$i]{$role}\n"; } }</code></pre> <h1 id="HASHES-OF-HASHES"><a class="permalink" href="#HASHES-OF-HASHES">#</a><a id="HASHES1"></a>HASHES OF HASHES </h1> <h2 id="Declaration-of-a-HASH-OF-HASHES"><a class="permalink" href="#Declaration-of-a-HASH-OF-HASHES">#</a><a id="Declaration3"></a>Declaration of a HASH OF HASHES</h2> <pre><code> %HoH = ( flintstones => { lead => "fred", pal => "barney", }, jetsons => { lead => "george", wife => "jane", "his boy" => "elroy", }, simpsons => { lead => "homer", wife => "marge", kid => "bart", }, );</code></pre> <h2 id="Generation-of-a-HASH-OF-HASHES"><a class="permalink" href="#Generation-of-a-HASH-OF-HASHES">#</a><a id="Generation3"></a>Generation of a HASH OF HASHES</h2> <pre><code># reading from file # flintstones: lead=fred pal=barney wife=wilma pet=dino while ( <> ) { next unless s/^(.*?):\s*//; $who = $1; for $field ( split ) { ($key, $value) = split /=/, $field; $HoH{$who}{$key} = $value; } # reading from file; more temps while ( <> ) { next unless s/^(.*?):\s*//; $who = $1; $rec = {}; $HoH{$who} = $rec; for $field ( split ) { ($key, $value) = split /=/, $field; $rec->{$key} = $value; } } # calling a function that returns a key,value hash for $group ( "simpsons", "jetsons", "flintstones" ) { $HoH{$group} = { get_family($group) }; } # likewise, but using temps for $group ( "simpsons", "jetsons", "flintstones" ) { %members = get_family($group); $HoH{$group} = { %members }; } # append new members to an existing family %new_folks = ( wife => "wilma", pet => "dino", ); for $what (keys %new_folks) { $HoH{flintstones}{$what} = $new_folks{$what}; }</code></pre> <h2 id="Access-and-Printing-of-a-HASH-OF-HASHES"><a class="permalink" href="#Access-and-Printing-of-a-HASH-OF-HASHES">#</a><a id="Access3"></a>Access and Printing of a HASH OF HASHES</h2> <pre><code># one element $HoH{flintstones}{wife} = "wilma"; # another element $HoH{simpsons}{lead} =~ s/(\w)/\u$1/; # print the whole thing foreach $family ( keys %HoH ) { print "$family: { "; for $role ( keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # print the whole thing somewhat sorted foreach $family ( sort keys %HoH ) { print "$family: { "; for $role ( sort keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # print the whole thing sorted by number of members foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) { print "$family: { "; for $role ( sort keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } # establish a sort order (rank) for each role $i = 0; for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i } # now print the whole thing sorted by number of members foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) { print "$family: { "; # and print these according to rank order for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; }</code></pre> <h1 id="MORE-ELABORATE-RECORDS"><a class="permalink" href="#MORE-ELABORATE-RECORDS">#</a><a id="MORE"></a>MORE ELABORATE RECORDS </h1> <h2 id="Declaration-of-MORE-ELABORATE-RECORDS"><a class="permalink" href="#Declaration-of-MORE-ELABORATE-RECORDS">#</a><a id="Declaration4"></a>Declaration of MORE ELABORATE RECORDS</h2> <p>Here's a sample showing how to create and use a record whose fields are of many different sorts:</p> <pre><code> $rec = { TEXT => $string, SEQUENCE => [ @old_values ], LOOKUP => { %some_table }, THATCODE => \&some_function, THISCODE => sub { $_[0] ** $_[1] }, HANDLE => \*STDOUT, }; print $rec->{TEXT}; print $rec->{SEQUENCE}[0]; $last = pop @ { $rec->{SEQUENCE} }; print $rec->{LOOKUP}{"key"}; ($first_k, $first_v) = each %{ $rec->{LOOKUP} }; $answer = $rec->{THATCODE}->($arg); $answer = $rec->{THISCODE}->($arg1, $arg2); # careful of extra block braces on fh ref print { $rec->{HANDLE} } "a string\n"; use FileHandle; $rec->{HANDLE}->autoflush(1); $rec->{HANDLE}->print(" a string\n");</code></pre> <h2 id="Declaration-of-a-HASH-OF-COMPLEX-RECORDS"><a class="permalink" href="#Declaration-of-a-HASH-OF-COMPLEX-RECORDS">#</a><a id="Declaration5"></a>Declaration of a HASH OF COMPLEX RECORDS</h2> <pre><code>%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, }, ], }, );</code></pre> <h2 id="Generation-of-a-HASH-OF-COMPLEX-RECORDS"><a class="permalink" href="#Generation-of-a-HASH-OF-COMPLEX-RECORDS">#</a><a id="Generation4"></a>Generation of a HASH OF COMPLEX RECORDS</h2> <pre><code># 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's easiest to do that # here's a piece by piece build up $rec = {}; $rec->{series} = "flintstones"; $rec->{nights} = [ find_days() ]; @members = (); # assume this file in field=value syntax while (<>) { %fields = split /[\s=]+/; 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' records without having duplicate # records and thus update problems. ########################################################### foreach $family (keys %TV) { $rec = $TV{$family}; # temp pointer @kids = (); for $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 $family ( keys %TV ) { print "the $family"; print " is on during @{ $TV{$family}{nights} }\n"; print "its members are:\n"; for $who ( @{ $TV{$family}{members} } ) { print " $who->{name} ($who->{role}), age $who->{age}\n"; } print "it turns out that $TV{$family}{lead} has "; print scalar ( @{ $TV{$family}{kids} } ), " kids named "; print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } ); print "\n"; }</code></pre> <h1 id="Database-Ties"><a class="permalink" href="#Database-Ties">#</a><a id="Database"></a>Database Ties</h1> <p>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 GDBM and Berkeley DB 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 MLDBM module. Check your nearest CPAN site as described in <a href="/5.16.2/perlmodlib">perlmodlib</a> for source code to MLDBM.</p> <h1 id="SEE-ALSO"><a class="permalink" href="#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1> <p><a href="/5.16.2/perlref">perlref</a>, <a href="/5.16.2/perllol">perllol</a>, <a href="/5.16.2/perldata">perldata</a>, <a href="/5.16.2/perlobj">perlobj</a></p> <h1 id="AUTHOR"><a class="permalink" href="#AUTHOR">#</a>AUTHOR</h1> <p>Tom Christiansen <<i>tchrist@perl.com</i>></p> <p>Last update: Wed Oct 23 04:57:50 MET DST 1996</p> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>