{
    "mode": "man",
    "parameter": "perlreftut",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlreftut/1/json",
    "generated": "2026-06-13T21:41:16Z",
    "sections": {
        "NAME": {
            "content": "perlreftut - Mark's very short tutorial about references\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "One of the most important new features in Perl 5 was the capability to manage complicated\ndata structures like multidimensional arrays and nested hashes.  To enable these, Perl 5\nintroduced a feature called references, and using references is the key to managing\ncomplicated, structured data in Perl.  Unfortunately, there's a lot of funny syntax to learn,\nand the main manual page can be hard to follow.  The manual is quite complete, and sometimes\npeople find that a problem, because it can be hard to tell what is important and what isn't.\n\nFortunately, you only need to know 10% of what's in the main page to get 90% of the benefit.\nThis page will show you that 10%.\n",
            "subsections": [
                {
                    "name": "Who Needs Complicated Data Structures?",
                    "content": "One problem that comes up all the time is needing a hash whose values are lists.  Perl has\nhashes, of course, but the values have to be scalars; they can't be lists.\n\nWhy would you want a hash of lists?  Let's take a simple example: You have a file of city and\ncountry names, like this:\n\nChicago, USA\nFrankfurt, Germany\nBerlin, Germany\nWashington, USA\nHelsinki, Finland\nNew York, USA\n\nand you want to produce an output like this, with each country mentioned once, and then an\nalphabetical list of the cities in that country:\n\nFinland: Helsinki.\nGermany: Berlin, Frankfurt.\nUSA:  Chicago, New York, Washington.\n\nThe natural way to do this is to have a hash whose keys are country names.  Associated with\neach country name key is a list of the cities in that country.  Each time you read a line of\ninput, split it into a country and a city, look up the list of cities already known to be in\nthat country, and append the new city to the list.  When you're done reading the input,\niterate over the hash as usual, sorting each list of cities before you print it out.\n\nIf hash values couldn't be lists, you lose.  You'd probably have to combine all the cities\ninto a single string somehow, and then when time came to write the output, you'd have to\nbreak the string into a list, sort the list, and turn it back into a string.  This is messy\nand error-prone.  And it's frustrating, because Perl already has perfectly good lists that\nwould solve the problem if only you could use them.\n"
                },
                {
                    "name": "The Solution",
                    "content": "By the time Perl 5 rolled around, we were already stuck with this design: Hash values must be\nscalars.  The solution to this is references.\n\nA reference is a scalar value that refers to an entire array or an entire hash (or to just\nabout anything else).  Names are one kind of reference that you're already familiar with.\nEach human being is a messy, inconvenient collection of cells. But to refer to a particular\nhuman, for instance the first computer programmer, it isn't necessary to describe each of\ntheir cells; all you need is the easy, convenient scalar string \"Ada Lovelace\".\n\nReferences in Perl are like names for arrays and hashes.  They're Perl's private, internal\nnames, so you can be sure they're unambiguous.  Unlike a human name, a reference only refers\nto one thing, and you always know what it refers to.  If you have a reference to an array,\nyou can recover the entire array from it.  If you have a reference to a hash, you can recover\nthe entire hash.  But the reference is still an easy, compact scalar value.\n\nYou can't have a hash whose values are arrays; hash values can only be scalars.  We're stuck\nwith that.  But a single reference can refer to an entire array, and references are scalars,\nso you can have a hash of references to arrays, and it'll act a lot like a hash of arrays,\nand it'll be just as useful as a hash of arrays.\n\nWe'll come back to this city-country problem later, after we've seen some syntax for managing\nreferences.\n"
                }
            ]
        },
        "Syntax": {
            "content": "There are just two ways to make a reference, and just two ways to use it once you have it.\n",
            "subsections": [
                {
                    "name": "Making References",
                    "content": "MMaakkee RRuullee 11\n\nIf you put a \"\\\" in front of a variable, you get a reference to that variable.\n\n$aref = \\@array;         # $aref now holds a reference to @array\n$href = \\%hash;          # $href now holds a reference to %hash\n$sref = \\$scalar;        # $sref now holds a reference to $scalar\n\nOnce the reference is stored in a variable like $aref or $href, you can copy it or store it\njust the same as any other scalar value:\n\n$xy = $aref;             # $xy now holds a reference to @array\n$p[3] = $href;           # $p[3] now holds a reference to %hash\n$z = $p[3];              # $z now holds a reference to %hash\n\nThese examples show how to make references to variables with names.  Sometimes you want to\nmake an array or a hash that doesn't have a name.  This is analogous to the way you like to\nbe able to use the string \"\\n\" or the number 80 without having to store it in a named\nvariable first.\n\nMMaakkee RRuullee 22\n\n\"[ ITEMS ]\" makes a new, anonymous array, and returns a reference to that array.  \"{ ITEMS }\"\nmakes a new, anonymous hash, and returns a reference to that hash.\n\n$aref = [ 1, \"foo\", undef, 13 ];\n# $aref now holds a reference to an array\n\n$href = { APR => 4, AUG => 8 };\n# $href now holds a reference to a hash\n\nThe references you get from rule 2 are the same kind of references that you get from rule 1:\n\n# This:\n$aref = [ 1, 2, 3 ];\n\n# Does the same as this:\n@array = (1, 2, 3);\n$aref = \\@array;\n\nThe first line is an abbreviation for the following two lines, except that it doesn't create\nthe superfluous array variable @array.\n\nIf you write just \"[]\", you get a new, empty anonymous array.  If you write just \"{}\", you\nget a new, empty anonymous hash.\n"
                },
                {
                    "name": "Using References",
                    "content": "What can you do with a reference once you have it?  It's a scalar value, and we've seen that\nyou can store it as a scalar and get it back again just like any scalar.  There are just two\nmore ways to use it:\n\nUUssee RRuullee 11\n\nYou can always use an array reference, in curly braces, in place of the name of an array.\nFor example, \"@{$aref}\" instead of @array.\n\nHere are some examples of that:\n\nArrays:\n\n@a              @{$aref}                An array\nreverse @a      reverse @{$aref}        Reverse the array\n$a[3]           ${$aref}[3]             An element of the array\n$a[3] = 17;     ${$aref}[3] = 17        Assigning an element\n\nOn each line are two expressions that do the same thing.  The left-hand versions operate on\nthe array @a.  The right-hand versions operate on the array that is referred to by $aref.\nOnce they find the array they're operating on, both versions do the same things to the\narrays.\n\nUsing a hash reference is exactly the same:\n\n%h              %{$href}              A hash\nkeys %h         keys %{$href}         Get the keys from the hash\n$h{'red'}       ${$href}{'red'}       An element of the hash\n$h{'red'} = 17  ${$href}{'red'} = 17  Assigning an element\n\nWhatever you want to do with a reference, Use Rule 1 tells you how to do it.  You just write\nthe Perl code that you would have written for doing the same thing to a regular array or\nhash, and then replace the array or hash name with \"{$reference}\".  \"How do I loop over an\narray when all I have is a reference?\"  Well, to loop over an array, you would write\n\nfor my $element (@array) {\n...\n}\n\nso replace the array name, @array, with the reference:\n\nfor my $element (@{$aref}) {\n...\n}\n\n\"How do I print out the contents of a hash when all I have is a reference?\"  First write the\ncode for printing out a hash:\n\nfor my $key (keys %hash) {\nprint \"$key => $hash{$key}\\n\";\n}\n\nAnd then replace the hash name with the reference:\n\nfor my $key (keys %{$href}) {\nprint \"$key => ${$href}{$key}\\n\";\n}\n\nUUssee RRuullee 22\n\nUse Rule 1 is all you really need, because it tells you how to do absolutely everything you\never need to do with references.  But the most common thing to do with an array or a hash is\nto extract a single element, and the Use Rule 1 notation is cumbersome.  So there is an\nabbreviation.\n\n\"${$aref}[3]\" is too hard to read, so you can write \"$aref->[3]\" instead.\n\n\"${$href}{red}\" is too hard to read, so you can write \"$href->{red}\" instead.\n\nIf $aref holds a reference to an array, then \"$aref->[3]\" is the fourth element of the array.\nDon't confuse this with $aref[3], which is the fourth element of a totally different array,\none deceptively named @aref.  $aref and @aref are unrelated the same way that $item and @item\nare.\n\nSimilarly, \"$href->{'red'}\" is part of the hash referred to by the scalar variable $href,\nperhaps even one with no name.  $href{'red'} is part of the deceptively named %href hash.\nIt's easy to forget to leave out the \"->\", and if you do, you'll get bizarre results when\nyour program gets array and hash elements out of totally unexpected hashes and arrays that\nweren't the ones you wanted to use.\n"
                },
                {
                    "name": "An Example",
                    "content": "Let's see a quick example of how all this is useful.\n\nFirst, remember that \"[1, 2, 3]\" makes an anonymous array containing \"(1, 2, 3)\", and gives\nyou a reference to that array.\n\nNow think about\n\n@a = ( [1, 2, 3],\n[4, 5, 6],\n[7, 8, 9]\n);\n\n@a is an array with three elements, and each one is a reference to another array.\n\n$a[1] is one of these references.  It refers to an array, the array containing \"(4, 5, 6)\",\nand because it is a reference to an array, Use Rule 2 says that we can write $a[1]->[2] to\nget the third element from that array.  $a[1]->[2] is the 6.  Similarly, $a[0]->[1] is the 2.\nWhat we have here is like a two-dimensional array; you can write $a[ROW]->[COLUMN] to get or\nset the element in any row and any column of the array.\n\nThe notation still looks a little cumbersome, so there's one more abbreviation:\n"
                },
                {
                    "name": "Arrow Rule",
                    "content": "In between two subscripts, the arrow is optional.\n\nInstead of $a[1]->[2], we can write $a[1][2]; it means the same thing.  Instead of\n\"$a[0]->[1] = 23\", we can write \"$a[0][1] = 23\"; it means the same thing.\n\nNow it really looks like two-dimensional arrays!\n\nYou can see why the arrows are important.  Without them, we would have had to write\n\"${$a[1]}[2]\" instead of $a[1][2].  For three-dimensional arrays, they let us write\n$x[2][3][5] instead of the unreadable \"${${$x[2]}[3]}[5]\".\n"
                }
            ]
        },
        "Solution": {
            "content": "Here's the answer to the problem I posed earlier, of reformatting a file of city and country\nnames.\n\n1   my %table;\n\n2   while (<>) {\n3     chomp;\n4     my ($city, $country) = split /, /;\n5     $table{$country} = [] unless exists $table{$country};\n6     push @{$table{$country}}, $city;\n7   }\n\n8   for my $country (sort keys %table) {\n9     print \"$country: \";\n10     my @cities = @{$table{$country}};\n11     print join ', ', sort @cities;\n12     print \".\\n\";\n13   }\n\nThe program has two pieces: Lines 2-7 read the input and build a data structure, and lines\n8-13 analyze the data and print out the report.  We're going to have a hash, %table, whose\nkeys are country names, and whose values are references to arrays of city names.  The data\nstructure will look like this:\n\n%table\n+-------+---+\n|       |   |   +-----------+--------+\n|Germany| *---->| Frankfurt | Berlin |\n|       |   |   +-----------+--------+\n+-------+---+\n|       |   |   +----------+\n|Finland| *---->| Helsinki |\n|       |   |   +----------+\n+-------+---+\n|       |   |   +---------+------------+----------+\n|  USA  | *---->| Chicago | Washington | New York |\n|       |   |   +---------+------------+----------+\n+-------+---+\n\nWe'll look at output first.  Supposing we already have this structure, how do we print it\nout?\n\n8   for my $country (sort keys %table) {\n9     print \"$country: \";\n10     my @cities = @{$table{$country}};\n11     print join ', ', sort @cities;\n12     print \".\\n\";\n13   }\n\n%table is an ordinary hash, and we get a list of keys from it, sort the keys, and loop over\nthe keys as usual.  The only use of references is in line 10.  $table{$country} looks up the\nkey $country in the hash and gets the value, which is a reference to an array of cities in\nthat country.  Use Rule 1 says that we can recover the array by saying \"@{$table{$country}}\".\nLine 10 is just like\n\n@cities = @array;\n\nexcept that the name \"array\" has been replaced by the reference \"{$table{$country}}\".  The\n\"@\" tells Perl to get the entire array.  Having gotten the list of cities, we sort it, join\nit, and print it out as usual.\n\nLines 2-7 are responsible for building the structure in the first place.  Here they are\nagain:\n\n2   while (<>) {\n3     chomp;\n4     my ($city, $country) = split /, /;\n5     $table{$country} = [] unless exists $table{$country};\n6     push @{$table{$country}}, $city;\n7   }\n\nLines 2-4 acquire a city and country name.  Line 5 looks to see if the country is already\npresent as a key in the hash.  If it's not, the program uses the \"[]\" notation (Make Rule 2)\nto manufacture a new, empty anonymous array of cities, and installs a reference to it into\nthe hash under the appropriate key.\n\nLine 6 installs the city name into the appropriate array.  $table{$country} now holds a\nreference to the array of cities seen in that country so far.  Line 6 is exactly like\n\npush @array, $city;\n\nexcept that the name \"array\" has been replaced by the reference \"{$table{$country}}\".  The\n\"push\" adds a city name to the end of the referred-to array.\n\nThere's one fine point I skipped.  Line 5 is unnecessary, and we can get rid of it.\n\n2   while (<>) {\n3     chomp;\n4     my ($city, $country) = split /, /;\n5   ####  $table{$country} = [] unless exists $table{$country};\n6     push @{$table{$country}}, $city;\n7   }\n\nIf there's already an entry in %table for the current $country, then nothing is different.\nLine 6 will locate the value in $table{$country}, which is a reference to an array, and push\n$city into the array.  But what does it do when $country holds a key, say \"Greece\", that is\nnot yet in %table?\n\nThis is Perl, so it does the exact right thing.  It sees that you want to push \"Athens\" onto\nan array that doesn't exist, so it helpfully makes a new, empty, anonymous array for you,\ninstalls it into %table, and then pushes \"Athens\" onto it.  This is called\nautovivification--bringing things to life automatically.  Perl saw that the key wasn't in the\nhash, so it created a new hash entry automatically. Perl saw that you wanted to use the hash\nvalue as an array, so it created a new empty array and installed a reference to it in the\nhash automatically.  And as usual, Perl made the array one element longer to hold the new\ncity name.\n",
            "subsections": [
                {
                    "name": "The Rest",
                    "content": "I promised to give you 90% of the benefit with 10% of the details, and that means I left out\n90% of the details.  Now that you have an overview of the important parts, it should be\neasier to read the perlref manual page, which discusses 100% of the details.\n\nSome of the highlights of perlref:\n\n•   You can make references to anything, including scalars, functions, and other references.\n\n•   In Use Rule 1, you can omit the curly brackets whenever the thing inside them is an\natomic scalar variable like $aref.  For example, @$aref is the same as \"@{$aref}\", and\n$$aref[1] is the same as \"${$aref}[1]\".  If you're just starting out, you may want to\nadopt the habit of always including the curly brackets.\n\n•   This doesn't copy the underlying array:\n\n$aref2 = $aref1;\n\nYou get two references to the same array.  If you modify \"$aref1->[23]\" and then look at\n\"$aref2->[23]\" you'll see the change.\n\nTo copy the array, use\n\n$aref2 = [@{$aref1}];\n\nThis uses \"[...]\" notation to create a new anonymous array, and $aref2 is assigned a\nreference to the new array.  The new array is initialized with the contents of the array\nreferred to by $aref1.\n\nSimilarly, to copy an anonymous hash, you can use\n\n$href2 = {%{$href1}};\n\n•   To see if a variable contains a reference, use the \"ref\" function.  It returns true if\nits argument is a reference.  Actually it's a little better than that: It returns \"HASH\"\nfor hash references and \"ARRAY\" for array references.\n\n•   If you try to use a reference like a string, you get strings like\n\nARRAY(0x80f5dec)   or    HASH(0x826afc0)\n\nIf you ever see a string that looks like this, you'll know you printed out a reference by\nmistake.\n\nA side effect of this representation is that you can use \"eq\" to see if two references\nrefer to the same thing.  (But you should usually use \"==\" instead because it's much\nfaster.)\n\n•   You can use a string as if it were a reference.  If you use the string \"foo\" as an array\nreference, it's taken to be a reference to the array @foo.  This is called a symbolic\nreference.  The declaration \"use strict 'refs'\" disables this feature, which can cause\nall sorts of trouble if you use it by accident.\n\nYou might prefer to go on to perllol instead of perlref; it discusses lists of lists and\nmultidimensional arrays in detail.  After that, you should move on to perldsc; it's a Data\nStructure Cookbook that shows recipes for using and printing out arrays of hashes, hashes of\narrays, and other kinds of data.\n"
                }
            ]
        },
        "Summary": {
            "content": "Everyone needs compound data structures, and in Perl the way you get them is with references.\nThere are four important rules for managing references: Two for making references and two for\nusing them.  Once you know these rules you can do most of the important things you need to do\nwith references.\n",
            "subsections": []
        },
        "Credits": {
            "content": "Author: Mark Jason Dominus, Plover Systems (\"mjd-perl-ref+@plover.com\")\n\nThis article originally appeared in The Perl Journal ( <http://www.tpj.com/> ) volume 3, #2.\nReprinted with permission.\n\nThe original title was Understand References Today.\n",
            "subsections": [
                {
                    "name": "Distribution Conditions",
                    "content": "Copyright 1998 The Perl Journal.\n\nThis documentation is free; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nIrrespective of its distribution, all code examples in these files are hereby placed into the\npublic domain.  You are permitted and encouraged to use this code in your own programs for\nfun or for profit as you see fit.  A simple comment in the code giving credit would be\ncourteous but is not required.\n\n\n\nperl v5.34.0                                 2025-07-25                                PERLREFTUT(1)"
                }
            ]
        }
    },
    "summary": "perlreftut - Mark's very short tutorial about references",
    "flags": [],
    "examples": [],
    "see_also": []
}