{
    "mode": "man",
    "parameter": "perlref",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perlref/1/json",
    "generated": "2026-06-02T23:32:57Z",
    "sections": {
        "NAME": {
            "content": "perlref - Perl references and nested data structures\n",
            "subsections": []
        },
        "NOTE": {
            "content": "This is complete documentation about all aspects of references.  For a shorter, tutorial\nintroduction to just the essential features, see perlreftut.\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "Before release 5 of Perl it was difficult to represent complex data structures, because all\nreferences had to be symbolic--and even then it was difficult to refer to a variable instead\nof a symbol table entry.  Perl now not only makes it easier to use symbolic references to\nvariables, but also lets you have \"hard\" references to any piece of data or code.  Any scalar\nmay hold a hard reference.  Because arrays and hashes contain scalars, you can now easily\nbuild arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions,\nand so on.\n\nHard references are smart--they keep track of reference counts for you, automatically freeing\nthe thing referred to when its reference count goes to zero.  (Reference counts for values in\nself-referential or cyclic data structures may not go to zero without a little help; see\n\"Circular References\" for a detailed explanation.)  If that thing happens to be an object,\nthe object is destructed.  See perlobj for more about objects.  (In a sense, everything in\nPerl is an object, but we usually reserve the word for references to objects that have been\nofficially \"blessed\" into a class package.)\n\nSymbolic references are names of variables or other objects, just as a symbolic link in a\nUnix filesystem contains merely the name of a file.  The *glob notation is something of a\nsymbolic reference.  (Symbolic references are sometimes called \"soft references\", but please\ndon't call them that; references are confusing enough without useless synonyms.)\n\nIn contrast, hard references are more like hard links in a Unix file system: They are used to\naccess an underlying object without concern for what its (other) name is.  When the word\n\"reference\" is used without an adjective, as in the following paragraph, it is usually\ntalking about a hard reference.\n\nReferences are easy to use in Perl.  There is just one overriding principle: in general, Perl\ndoes no implicit referencing or dereferencing.  When a scalar is holding a reference, it\nalways behaves as a simple scalar.  It doesn't magically start being an array or hash or\nsubroutine; you have to tell it explicitly to do so, by dereferencing it.\n",
            "subsections": [
                {
                    "name": "Making References",
                    "content": "References can be created in several ways.\n\nBackslash Operator\n\nBy using the backslash operator on a variable, subroutine, or value.  (This works much like\nthe & (address-of) operator in C.)  This typically creates another reference to a variable,\nbecause there's already a reference to the variable in the symbol table.  But the symbol\ntable reference might go away, and you'll still have the reference that the backslash\nreturned.  Here are some examples:\n\n$scalarref = \\$foo;\n$arrayref  = \\@ARGV;\n$hashref   = \\%ENV;\n$coderef   = \\&handler;\n$globref   = \\*foo;\n\nIt isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using\nthe backslash operator.  The most you can get is a reference to a typeglob, which is actually\na complete symbol table entry.  But see the explanation of the *foo{THING} syntax below.\nHowever, you can still use type globs and globrefs as though they were IO handles.\n\nSquare Brackets\n\nA reference to an anonymous array can be created using square brackets:\n\n$arrayref = [1, 2, ['a', 'b', 'c']];\n\nHere we've created a reference to an anonymous array of three elements whose final element is\nitself a reference to another anonymous array of three elements.  (The multidimensional\nsyntax described later can be used to access this.  For example, after the above,\n\"$arrayref->[2][1]\" would have the value \"b\".)\n\nTaking a reference to an enumerated list is not the same as using square brackets--instead\nit's the same as creating a list of references!\n\n@list = (\\$a, \\@b, \\%c);\n@list = \\($a, @b, %c);      # same thing!\n\nAs a special case, \"\\(@foo)\" returns a list of references to the contents of @foo, not a\nreference to @foo itself.  Likewise for %foo, except that the key references are to copies\n(since the keys are just strings rather than full-fledged scalars).\n\nCurly Brackets\n\nA reference to an anonymous hash can be created using curly brackets:\n\n$hashref = {\n'Adam'  => 'Eve',\n'Clyde' => 'Bonnie',\n};\n\nAnonymous hash and array composers like these can be intermixed freely to produce as\ncomplicated a structure as you want.  The multidimensional syntax described below works for\nthese too.  The values above are literals, but variables and expressions would work just as\nwell, because assignment operators in Perl (even within local() or my()) are executable\nstatements, not compile-time declarations.\n\nBecause curly brackets (braces) are used for several other things including BLOCKs, you may\noccasionally have to disambiguate braces at the beginning of a statement by putting a \"+\" or\na \"return\" in front so that Perl realizes the opening brace isn't starting a BLOCK.  The\neconomy and mnemonic value of using curlies is deemed worth this occasional extra hassle.\n\nFor example, if you wanted a function to make a new hash and return a reference to it, you\nhave these options:\n\nsub hashem {        { @ } }   # silently wrong\nsub hashem {       +{ @ } }   # ok\nsub hashem { return { @ } }   # ok\n\nOn the other hand, if you want the other meaning, you can do this:\n\nsub showem {        { @ } }   # ambiguous (currently ok,\n# but may change)\nsub showem {       {; @ } }   # ok\nsub showem { { return @ } }   # ok\n\nThe leading \"+{\" and \"{;\" always serve to disambiguate the expression to mean either the HASH\nreference, or the BLOCK.\n\nAnonymous Subroutines\n\nA reference to an anonymous subroutine can be created by using \"sub\" without a subname:\n\n$coderef = sub { print \"Boink!\\n\" };\n\nNote the semicolon.  Except for the code inside not being immediately executed, a \"sub {}\" is\nnot so much a declaration as it is an operator, like \"do{}\" or \"eval{}\".  (However, no matter\nhow many times you execute that particular line (unless you're in an \"eval(\"...\")\"), $coderef\nwill still have a reference to the same anonymous subroutine.)\n\nAnonymous subroutines act as closures with respect to my() variables, that is, variables\nlexically visible within the current scope.  Closure is a notion out of the Lisp world that\nsays if you define an anonymous function in a particular lexical context, it pretends to run\nin that context even when it's called outside the context.\n\nIn human terms, it's a funny way of passing arguments to a subroutine when you define it as\nwell as when you call it.  It's useful for setting up little bits of code to run later, such\nas callbacks.  You can even do object-oriented stuff with it, though Perl already provides a\ndifferent mechanism to do that--see perlobj.\n\nYou might also think of closure as a way to write a subroutine template without using eval().\nHere's a small example of how closures work:\n\nsub newprint {\nmy $x = shift;\nreturn sub { my $y = shift; print \"$x, $y!\\n\"; };\n}\n$h = newprint(\"Howdy\");\n$g = newprint(\"Greetings\");\n\n# Time passes...\n\n&$h(\"world\");\n&$g(\"earthlings\");\n\nThis prints\n\nHowdy, world!\nGreetings, earthlings!\n\nNote particularly that $x continues to refer to the value passed into newprint() despite \"my\n$x\" having gone out of scope by the time the anonymous subroutine runs.  That's what a\nclosure is all about.\n\nThis applies only to lexical variables, by the way.  Dynamic variables continue to work as\nthey have always worked.  Closure is not something that most Perl programmers need trouble\nthemselves about to begin with.\n\nConstructors\n\nReferences are often returned by special subroutines called constructors.  Perl objects are\njust references to a special type of object that happens to know which package it's\nassociated with.  Constructors are just special subroutines that know how to create that\nassociation.  They do so by starting with an ordinary reference, and it remains an ordinary\nreference even while it's also being an object.  Constructors are often named \"new()\".  You\ncan call them indirectly:\n\n$objref = new Doggie( Tail => 'short', Ears => 'long' );\n\nBut that can produce ambiguous syntax in certain cases, so it's often better to use the\ndirect method invocation approach:\n\n$objref   = Doggie->new(Tail => 'short', Ears => 'long');\n\nuse Term::Cap;\n$terminal = Term::Cap->Tgetent( { OSPEED => 9600 });\n\nuse Tk;\n$main    = MainWindow->new();\n$menubar = $main->Frame(-relief              => \"raised\",\n-borderwidth         => 2)\n\nAutovivification\n\nReferences of the appropriate type can spring into existence if you dereference them in a\ncontext that assumes they exist.  Because we haven't talked about dereferencing yet, we can't\nshow you any examples yet.\n\nTypeglob Slots\n\nA reference can be created by using a special syntax, lovingly known as the *foo{THING}\nsyntax.  *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table\nentry which holds everything known as foo).\n\n$scalarref = *foo{SCALAR};\n$arrayref  = *ARGV{ARRAY};\n$hashref   = *ENV{HASH};\n$coderef   = *handler{CODE};\n$ioref     = *STDIN{IO};\n$globref   = *foo{GLOB};\n$formatref = *foo{FORMAT};\n$globname  = *foo{NAME};    # \"foo\"\n$pkgname   = *foo{PACKAGE}; # \"main\"\n\nMost of these are self-explanatory, but *foo{IO} deserves special attention.  It returns the\nIO handle, used for file handles (\"open\" in perlfunc), sockets (\"socket\" in perlfunc and\n\"socketpair\" in perlfunc), and directory handles (\"opendir\" in perlfunc).  For compatibility\nwith previous versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}, though it is\ndiscouraged, to encourage a consistent use of one name: IO.  On perls between v5.8 and v5.22,\nit will issue a deprecation warning, but this deprecation has since been rescinded.\n\n*foo{THING} returns undef if that particular THING hasn't been used yet, except in the case\nof scalars.  *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used\nyet.  This might change in a future release.\n\n*foo{NAME} and *foo{PACKAGE} are the exception, in that they return strings, rather than\nreferences.  These return the package and name of the typeglob itself, rather than one that\nhas been assigned to it.  So, after \"*foo=*Foo::bar\", *foo will become \"*Foo::bar\" when used\nas a string, but *foo{PACKAGE} and *foo{NAME} will continue to produce \"main\" and \"foo\",\nrespectively.\n\n*foo{IO} is an alternative to the *HANDLE mechanism given in \"Typeglobs and Filehandles\" in\nperldata for passing filehandles into or out of subroutines, or storing into larger data\nstructures.  Its disadvantage is that it won't create a new filehandle for you.  Its\nadvantage is that you have less risk of clobbering more than you want to with a typeglob\nassignment.  (It still conflates file and directory handles, though.)  However, if you assign\nthe incoming value to a scalar instead of a typeglob as we do in the examples below, there's\nno risk of that happening.\n\nsplutter(*STDOUT);          # pass the whole glob\nsplutter(*STDOUT{IO});      # pass both file and dir handles\n\nsub splutter {\nmy $fh = shift;\nprint $fh \"her um well a hmmm\\n\";\n}\n\n$rec = getrec(*STDIN);     # pass the whole glob\n$rec = getrec(*STDIN{IO}); # pass both file and dir handles\n\nsub getrec {\nmy $fh = shift;\nreturn scalar <$fh>;\n}\n"
                },
                {
                    "name": "Using References",
                    "content": "That's it for creating references.  By now you're probably dying to know how to use\nreferences to get back to your long-lost data.  There are several basic methods.\n\nSimple Scalar\n\nAnywhere you'd put an identifier (or chain of identifiers) as part of a variable or\nsubroutine name, you can replace the identifier with a simple scalar variable containing a\nreference of the correct type:\n\n$bar = $$scalarref;\npush(@$arrayref, $filename);\n$$arrayref[0] = \"January\";\n$$hashref{\"KEY\"} = \"VALUE\";\n&$coderef(1,2,3);\nprint $globref \"output\\n\";\n\nIt's important to understand that we are specifically not dereferencing $arrayref[0] or\n$hashref{\"KEY\"} there.  The dereference of the scalar variable happens before it does any key\nlookups.  Anything more complicated than a simple scalar variable must use methods 2 or 3\nbelow.  However, a \"simple scalar\" includes an identifier that itself uses method 1\nrecursively.  Therefore, the following prints \"howdy\".\n\n$refrefref = \\\\\\\"howdy\";\nprint $$$$refrefref;\n\nBlock\n\nAnywhere you'd put an identifier (or chain of identifiers) as part of a variable or\nsubroutine name, you can replace the identifier with a BLOCK returning a reference of the\ncorrect type.  In other words, the previous examples could be written like this:\n\n$bar = ${$scalarref};\npush(@{$arrayref}, $filename);\n${$arrayref}[0] = \"January\";\n${$hashref}{\"KEY\"} = \"VALUE\";\n&{$coderef}(1,2,3);\n$globref->print(\"output\\n\");  # iff IO::Handle is loaded\n\nAdmittedly, it's a little silly to use the curlies in this case, but the BLOCK can contain\nany arbitrary expression, in particular, subscripted expressions:\n\n&{ $dispatch{$index} }(1,2,3);      # call correct routine\n\nBecause of being able to omit the curlies for the simple case of $$x, people often make the\nmistake of viewing the dereferencing symbols as proper operators, and wonder about their\nprecedence.  If they were, though, you could use parentheses instead of braces.  That's not\nthe case.  Consider the difference below; case 0 is a short-hand version of case 1, not case\n2:\n\n$$hashref{\"KEY\"}   = \"VALUE\";       # CASE 0\n${$hashref}{\"KEY\"} = \"VALUE\";       # CASE 1\n${$hashref{\"KEY\"}} = \"VALUE\";       # CASE 2\n${$hashref->{\"KEY\"}} = \"VALUE\";     # CASE 3\n\nCase 2 is also deceptive in that you're accessing a variable called %hashref, not\ndereferencing through $hashref to the hash it's presumably referencing.  That would be case\n3.\n\nArrow Notation\n\nSubroutine calls and lookups of individual array elements arise often enough that it gets\ncumbersome to use method 2.  As a form of syntactic sugar, the examples for method 2 may be\nwritten:\n\n$arrayref->[0] = \"January\";   # Array element\n$hashref->{\"KEY\"} = \"VALUE\";  # Hash element\n$coderef->(1,2,3);            # Subroutine call\n\nThe left side of the arrow can be any expression returning a reference, including a previous\ndereference.  Note that $array[$x] is not the same thing as \"$array->[$x]\" here:\n\n$array[$x]->{\"foo\"}->[0] = \"January\";\n\nThis is one of the cases we mentioned earlier in which references could spring into existence\nwhen in an lvalue context.  Before this statement, $array[$x] may have been undefined.  If\nso, it's automatically defined with a hash reference so that we can look up \"{\"foo\"}\" in it.\nLikewise \"$array[$x]->{\"foo\"}\" will automatically get defined with an array reference so that\nwe can look up \"[0]\" in it.  This process is called autovivification.\n\nOne more thing here.  The arrow is optional between brackets subscripts, so you can shrink\nthe above down to\n\n$array[$x]{\"foo\"}[0] = \"January\";\n\nWhich, in the degenerate case of using only ordinary arrays, gives you multidimensional\narrays just like C's:\n\n$score[$x][$y][$z] += 42;\n\nWell, okay, not entirely like C's arrays, actually.  C doesn't know how to grow its arrays on\ndemand.  Perl does.\n\nObjects\n\nIf a reference happens to be a reference to an object, then there are probably methods to\naccess the things referred to, and you should probably stick to those methods unless you're\nin the class package that defines the object's methods.  In other words, be nice, and don't\nviolate the object's encapsulation without a very good reason.  Perl does not enforce\nencapsulation.  We are not totalitarians here.  We do expect some basic civility though.\n\nMiscellaneous Usage\n\nUsing a string or number as a reference produces a symbolic reference, as explained above.\nUsing a reference as a number produces an integer representing its storage location in\nmemory.  The only useful thing to be done with this is to compare two references numerically\nto see whether they refer to the same location.\n\nif ($ref1 == $ref2) {  # cheap numeric compare of references\nprint \"refs 1 and 2 refer to the same thing\\n\";\n}\n\nUsing a reference as a string produces both its referent's type, including any package\nblessing as described in perlobj, as well as the numeric address expressed in hex.  The ref()\noperator returns just the type of thing the reference is pointing to, without the address.\nSee \"ref\" in perlfunc for details and examples of its use.\n\nThe bless() operator may be used to associate the object a reference points to with a package\nfunctioning as an object class.  See perlobj.\n\nA typeglob may be dereferenced the same way a reference can, because the dereference syntax\nalways indicates the type of reference desired.  So \"${*foo}\" and \"${\\$foo}\" both indicate\nthe same scalar variable.\n\nHere's a trick for interpolating a subroutine call into a string:\n\nprint \"My sub returned @{[mysub(1,2,3)]} that time.\\n\";\n\nThe way it works is that when the \"@{...}\" is seen in the double-quoted string, it's\nevaluated as a block.  The block creates a reference to an anonymous array containing the\nresults of the call to \"mysub(1,2,3)\".  So the whole block returns a reference to an array,\nwhich is then dereferenced by \"@{...}\" and stuck into the double-quoted string. This\nchicanery is also useful for arbitrary expressions:\n\nprint \"That yields @{[$n + 5]} widgets\\n\";\n\nSimilarly, an expression that returns a reference to a scalar can be dereferenced via\n\"${...}\". Thus, the above expression may be written as:\n\nprint \"That yields ${\\($n + 5)} widgets\\n\";\n"
                },
                {
                    "name": "Circular References",
                    "content": "It is possible to create a \"circular reference\" in Perl, which can lead to memory leaks. A\ncircular reference occurs when two references contain a reference to each other, like this:\n\nmy $foo = {};\nmy $bar = { foo => $foo };\n$foo->{bar} = $bar;\n\nYou can also create a circular reference with a single variable:\n\nmy $foo;\n$foo = \\$foo;\n\nIn this case, the reference count for the variables will never reach 0, and the references\nwill never be garbage-collected. This can lead to memory leaks.\n\nBecause objects in Perl are implemented as references, it's possible to have circular\nreferences with objects as well. Imagine a TreeNode class where each node references its\nparent and child nodes. Any node with a parent will be part of a circular reference.\n\nYou can break circular references by creating a \"weak reference\". A weak reference does not\nincrement the reference count for a variable, which means that the object can go out of scope\nand be destroyed. You can weaken a reference with the \"weaken\" function exported by the\nScalar::Util module.\n\nHere's how we can make the first example safer:\n\nuse Scalar::Util 'weaken';\n\nmy $foo = {};\nmy $bar = { foo => $foo };\n$foo->{bar} = $bar;\n\nweaken $foo->{bar};\n\nThe reference from $foo to $bar has been weakened. When the $bar variable goes out of scope,\nit will be garbage-collected. The next time you look at the value of the \"$foo->{bar}\" key,\nit will be \"undef\".\n\nThis action at a distance can be confusing, so you should be careful with your use of weaken.\nYou should weaken the reference in the variable that will go out of scope first. That way,\nthe longer-lived variable will contain the expected reference until it goes out of scope.\n"
                },
                {
                    "name": "Symbolic references",
                    "content": "We said that references spring into existence as necessary if they are undefined, but we\ndidn't say what happens if a value used as a reference is already defined, but isn't a hard\nreference.  If you use it as a reference, it'll be treated as a symbolic reference.  That is,\nthe value of the scalar is taken to be the name of a variable, rather than a direct link to a\n(possibly) anonymous value.\n\nPeople frequently expect it to work like this.  So it does.\n\n$name = \"foo\";\n$$name = 1;                 # Sets $foo\n${$name} = 2;               # Sets $foo\n${$name x 2} = 3;           # Sets $foofoo\n$name->[0] = 4;             # Sets $foo[0]\n@$name = ();                # Clears @foo\n&$name();                   # Calls &foo()\n$pack = \"THAT\";\n${\"${pack}::$name\"} = 5;    # Sets $THAT::foo without eval\n\nThis is powerful, and slightly dangerous, in that it's possible to intend (with the utmost\nsincerity) to use a hard reference, and accidentally use a symbolic reference instead.  To\nprotect against that, you can say\n\nuse strict 'refs';\n\nand then only hard references will be allowed for the rest of the enclosing block.  An inner\nblock may countermand that with\n\nno strict 'refs';\n\nOnly package variables (globals, even if localized) are visible to symbolic references.\nLexical variables (declared with my()) aren't in a symbol table, and thus are invisible to\nthis mechanism.  For example:\n\nlocal $value = 10;\n$ref = \"value\";\n{\nmy $value = 20;\nprint $$ref;\n}\n\nThis will still print 10, not 20.  Remember that local() affects package variables, which are\nall \"global\" to the package.\n"
                },
                {
                    "name": "Not-so-symbolic references",
                    "content": "Brackets around a symbolic reference can simply serve to isolate an identifier or variable\nname from the rest of an expression, just as they always have within a string.  For example,\n\n$push = \"pop on \";\nprint \"${push}over\";\n\nhas always meant to print \"pop on over\", even though push is a reserved word.  This is\ngeneralized to work the same without the enclosing double quotes, so that\n\nprint ${push} . \"over\";\n\nand even\n\nprint ${ push } . \"over\";\n\nwill have the same effect.  This construct is not considered to be a symbolic reference when\nyou're using strict refs:\n\nuse strict 'refs';\n${ bareword };      # Okay, means $bareword.\n${ \"bareword\" };    # Error, symbolic reference.\n\nSimilarly, because of all the subscripting that is done using single words, the same rule\napplies to any bareword that is used for subscripting a hash.  So now, instead of writing\n\n$hash{ \"aaa\" }{ \"bbb\" }{ \"ccc\" }\n\nyou can write just\n\n$hash{ aaa }{ bbb }{ ccc }\n\nand not worry about whether the subscripts are reserved words.  In the rare event that you do\nwish to do something like\n\n$hash{ shift }\n\nyou can force interpretation as a reserved word by adding anything that makes it more than a\nbareword:\n\n$hash{ shift() }\n$hash{ +shift }\n$hash{ shift @ }\n\nThe \"use warnings\" pragma or the -w switch will warn you if it interprets a reserved word as\na string.  But it will no longer warn you about using lowercase words, because the string is\neffectively quoted.\n"
                },
                {
                    "name": "Pseudo-hashes: Using an array as a hash",
                    "content": "Pseudo-hashes have been removed from Perl.  The 'fields' pragma remains available.\n"
                },
                {
                    "name": "Function Templates",
                    "content": "As explained above, an anonymous function with access to the lexical variables visible when\nthat function was compiled, creates a closure.  It retains access to those variables even\nthough it doesn't get run until later, such as in a signal handler or a Tk callback.\n\nUsing a closure as a function template allows us to generate many functions that act\nsimilarly.  Suppose you wanted functions named after the colors that generated HTML font\nchanges for the various colors:\n\nprint \"Be \", red(\"careful\"), \"with that \", green(\"light\");\n\nThe red() and green() functions would be similar.  To create these, we'll assign a closure to\na typeglob of the name of the function we're trying to build.\n\n@colors = qw(red blue green yellow orange purple violet);\nfor my $name (@colors) {\nno strict 'refs';       # allow symbol table manipulation\n*$name = *{uc $name} = sub { \"<FONT COLOR='$name'>@</FONT>\" };\n}\n\nNow all those different functions appear to exist independently.  You can call red(), RED(),\nblue(), BLUE(), green(), etc.  This technique saves on both compile time and memory use, and\nis less error-prone as well, since syntax checks happen at compile time.  It's critical that\nany variables in the anonymous subroutine be lexicals in order to create a proper closure.\nThat's the reasons for the \"my\" on the loop iteration variable.\n\nThis is one of the only places where giving a prototype to a closure makes much sense.  If\nyou wanted to impose scalar context on the arguments of these functions (probably not a wise\nidea for this particular example), you could have written it this way instead:\n\n*$name = sub ($) { \"<FONT COLOR='$name'>$[0]</FONT>\" };\n\nHowever, since prototype checking happens at compile time, the assignment above happens too\nlate to be of much use.  You could address this by putting the whole loop of assignments\nwithin a BEGIN block, forcing it to occur during compilation.\n\nAccess to lexicals that change over time--like those in the \"for\" loop above, basically\naliases to elements from the surrounding lexical scopes-- only works with anonymous subs, not\nwith named subroutines. Generally said, named subroutines do not nest properly and should\nonly be declared in the main package scope.\n\nThis is because named subroutines are created at compile time so their lexical variables get\nassigned to the parent lexicals from the first execution of the parent block. If a parent\nscope is entered a second time, its lexicals are created again, while the nested subs still\nreference the old ones.\n\nAnonymous subroutines get to capture each time you execute the \"sub\" operator, as they are\ncreated on the fly. If you are accustomed to using nested subroutines in other programming\nlanguages with their own private variables, you'll have to work at it a bit in Perl.  The\nintuitive coding of this type of thing incurs mysterious warnings about \"will not stay\nshared\" due to the reasons explained above.  For example, this won't work:\n\nsub outer {\nmy $x = $[0] + 35;\nsub inner { return $x * 19 }   # WRONG\nreturn $x + inner();\n}\n\nA work-around is the following:\n\nsub outer {\nmy $x = $[0] + 35;\nlocal *inner = sub { return $x * 19 };\nreturn $x + inner();\n}\n\nNow inner() can only be called from within outer(), because of the temporary assignments of\nthe anonymous subroutine. But when it does, it has normal access to the lexical variable $x\nfrom the scope of outer() at the time outer is invoked.\n\nThis has the interesting effect of creating a function local to another function, something\nnot normally supported in Perl.\n"
                },
                {
                    "name": "Postfix Dereference Syntax",
                    "content": "Beginning in v5.20.0, a postfix syntax for using references is available.  It behaves as\ndescribed in \"Using References\", but instead of a prefixed sigil, a postfixed sigil-and-star\nis used.\n\nFor example:\n\n$r = \\@a;\n@b = $r->@*; # equivalent to @$r or @{ $r }\n\n$r = [ 1, [ 2, 3 ], 4 ];\n$r->[1]->@*;  # equivalent to @{ $r->[1] }\n\nIn Perl 5.20 and 5.22, this syntax must be enabled with \"use feature 'postderef'\". As of Perl\n5.24, no feature declarations are required to make it available.\n\nPostfix dereference should work in all circumstances where block (circumfix) dereference\nworked, and should be entirely equivalent.  This syntax allows dereferencing to be written\nand read entirely left-to-right.  The following equivalencies are defined:\n\n$sref->$*;  # same as  ${ $sref }\n$aref->@*;  # same as  @{ $aref }\n$aref->$#*; # same as $#{ $aref }\n$href->%*;  # same as  %{ $href }\n$cref->&*;  # same as  &{ $cref }\n$gref->;  # same as  *{ $gref }\n\nNote especially that \"$cref->&*\" is not equivalent to \"$cref->()\", and can serve different\npurposes.\n\nGlob elements can be extracted through the postfix dereferencing feature:\n\n$gref->*{SCALAR}; # same as *{ $gref }{SCALAR}\n\nPostfix array and scalar dereferencing can be used in interpolating strings (double quotes or\nthe \"qq\" operator), but only if the \"postderefqq\" feature is enabled.\n"
                },
                {
                    "name": "Postfix Reference Slicing",
                    "content": "Value slices of arrays and hashes may also be taken with postfix dereferencing notation, with\nthe following equivalencies:\n\n$aref->@[ ... ];  # same as @$aref[ ... ]\n$href->@{ ... };  # same as @$href{ ... }\n\nPostfix key/value pair slicing, added in 5.20.0 and documented in the Key/Value Hash Slices\nsection of perldata, also behaves as expected:\n\n$aref->%[ ... ];  # same as %$aref[ ... ]\n$href->%{ ... };  # same as %$href{ ... }\n\nAs with postfix array, postfix value slice dereferencing can be used in interpolating strings\n(double quotes or the \"qq\" operator), but only if the \"postderefqq\" feature is enabled.\n"
                },
                {
                    "name": "Assigning to References",
                    "content": "Beginning in v5.22.0, the referencing operator can be assigned to.  It performs an aliasing\noperation, so that the variable name referenced on the left-hand side becomes an alias for\nthe thing referenced on the right-hand side:\n\n\\$a = \\$b; # $a and $b now point to the same scalar\n\\&foo = \\&bar; # foo() now means bar()\n\nThis syntax must be enabled with \"use feature 'refaliasing'\".  It is experimental, and will\nwarn by default unless \"no warnings 'experimental::refaliasing'\" is in effect.\n\nThese forms may be assigned to, and cause the right-hand side to be evaluated in scalar\ncontext:\n\n\\$scalar\n\\@array\n\\%hash\n\\&sub\n\\my $scalar\n\\my @array\n\\my %hash\n\\state $scalar # or @array, etc.\n\\our $scalar   # etc.\n\\local $scalar # etc.\n\\local our $scalar # etc.\n\\$somearray[$index]\n\\$somehash{$key}\n\\local $somearray[$index]\n\\local $somehash{$key}\ncondition ? \\$this : \\$that[0] # etc.\n\nSlicing operations and parentheses cause the right-hand side to be evaluated in list context:\n\n\\@array[5..7]\n(\\@array[5..7])\n\\(@array[5..7])\n\\@hash{'foo','bar'}\n(\\@hash{'foo','bar'})\n\\(@hash{'foo','bar'})\n(\\$scalar)\n\\($scalar)\n\\(my $scalar)\n\\my($scalar)\n(\\@array)\n(\\%hash)\n(\\&sub)\n\\(&sub)\n\\($foo, @bar, %baz)\n(\\$foo, \\@bar, \\%baz)\n\nEach element on the right-hand side must be a reference to a datum of the right type.\nParentheses immediately surrounding an array (and possibly also \"my\"/\"state\"/\"our\"/\"local\")\nwill make each element of the array an alias to the corresponding scalar referenced on the\nright-hand side:\n\n\\(@a) = \\(@b); # @a and @b now have the same elements\n\\my(@a) = \\(@b); # likewise\n\\(my @a) = \\(@b); # likewise\npush @a, 3; # but now @a has an extra element that @b lacks\n\\(@a) = (\\$a, \\$b, \\$c); # @a now contains $a, $b, and $c\n\nCombining that form with \"local\" and putting parentheses immediately around a hash are\nforbidden (because it is not clear what they should do):\n\n\\local(@array) = foo(); # WRONG\n\\(%hash)       = bar(); # WRONG\n\nAssignment to references and non-references may be combined in lists and conditional ternary\nexpressions, as long as the values on the right-hand side are the right type for each element\non the left, though this may make for obfuscated code:\n\n(my $tom, \\my $dick, \\my @harry) = (\\1, \\2, [1..3]);\n# $tom is now \\1\n# $dick is now 2 (read-only)\n# @harry is (1,2,3)\n\nmy $type = ref $thingy;\n($type ? $type eq 'ARRAY' ? \\@foo : \\$bar : $baz) = $thingy;\n\nThe \"foreach\" loop can also take a reference constructor for its loop variable, though the\nsyntax is limited to one of the following, with an optional \"my\", \"state\", or \"our\" after the\nbackslash:\n\n\\$s\n\\@a\n\\%h\n\\&c\n\nNo parentheses are permitted.  This feature is particularly useful for arrays-of-arrays, or\narrays-of-hashes:\n\nforeach \\my @a (@arrayofarrays) {\nfrobnicate($a[0], $a[-1]);\n}\n\nforeach \\my %h (@arrayofhashes) {\n$h{gelastic}++ if $h{type} eq 'funny';\n}\n\nCAVEAT: Aliasing does not work correctly with closures.  If you try to alias lexical\nvariables from an inner subroutine or \"eval\", the aliasing will only be visible within that\ninner sub, and will not affect the outer subroutine where the variables are declared.  This\nbizarre behavior is subject to change.\n"
                },
                {
                    "name": "Declaring a Reference to a Variable",
                    "content": "Beginning in v5.26.0, the referencing operator can come after \"my\", \"state\", \"our\", or\n\"local\".  This syntax must be enabled with \"use feature 'declaredrefs'\".  It is\nexperimental, and will warn by default unless \"no warnings 'experimental::refaliasing'\" is in\neffect.\n\nThis feature makes these:\n\nmy \\$x;\nour \\$y;\n\nequivalent to:\n\n\\my $x;\n\\our $x;\n\nIt is intended mainly for use in assignments to references (see \"Assigning to References\",\nabove).  It also allows the backslash to be used on just some items in a list of declared\nvariables:\n\nmy ($foo, \\@bar, \\%baz); # equivalent to:  my $foo, \\my(@bar, %baz);\n"
                },
                {
                    "name": "WARNING: Don't use references as hash keys",
                    "content": "You may not (usefully) use a reference as the key to a hash.  It will be converted into a\nstring:\n\n$x{ \\$a } = $a;\n\nIf you try to dereference the key, it won't do a hard dereference, and you won't accomplish\nwhat you're attempting.  You might want to do something more like\n\n$r = \\@a;\n$x{ $r } = $r;\n\nAnd then at least you can use the values(), which will be real refs, instead of the keys(),\nwhich won't.\n\nThe standard Tie::RefHash module provides a convenient workaround to this.\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "Besides the obvious documents, source code can be instructive.  Some pathological examples of\nthe use of references can be found in the t/op/ref.t regression test in the Perl source\ndirectory.\n\nSee also perldsc and perllol for how to use references to create complex data structures, and\nperlootut and perlobj for how to use them to create objects.\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLREF(1)",
            "subsections": []
        }
    },
    "summary": "perlref - Perl references and nested data structures",
    "flags": [],
    "examples": [],
    "see_also": []
}