{
    "content": [
        {
            "type": "text",
            "text": "# perlref (perldoc)\n\n## NAME\n\nperlref - Perl references and nested data structures\n\n## DESCRIPTION\n\nBefore 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 of\na symbol table entry. Perl now not only makes it easier to use symbolic references to variables,\nbut also lets you have \"hard\" references to any piece of data or code. Any scalar may hold a\nhard reference. Because arrays and hashes contain scalars, you can now easily build arrays of\narrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on.\n\n## Sections\n\n- **NAME**\n- **NOTE**\n- **DESCRIPTION** (12 subsections)\n- **SEE ALSO**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "perlref",
        "section": "",
        "mode": "perldoc",
        "summary": "perlref - Perl references and nested data structures",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "NOTE",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 30,
                "subsections": [
                    {
                        "name": "Making References",
                        "lines": 207
                    },
                    {
                        "name": "Using References",
                        "lines": 133
                    },
                    {
                        "name": "Circular References",
                        "lines": 42
                    },
                    {
                        "name": "Symbolic references",
                        "lines": 43
                    },
                    {
                        "name": "Not-so-symbolic references",
                        "lines": 47
                    },
                    {
                        "name": "Pseudo-hashes: Using an array as a hash",
                        "lines": 2
                    },
                    {
                        "name": "Function Templates",
                        "lines": 20
                    },
                    {
                        "name": "blue",
                        "lines": 51
                    },
                    {
                        "name": "Postfix Dereference Syntax",
                        "lines": 36
                    },
                    {
                        "name": "Postfix Reference Slicing",
                        "lines": 15
                    },
                    {
                        "name": "Assigning to References",
                        "lines": 102
                    },
                    {
                        "name": "Declaring a Reference to a Variable",
                        "lines": 36
                    }
                ]
            },
            {
                "name": "SEE ALSO",
                "lines": 6,
                "subsections": []
            }
        ],
        "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 of\na symbol table entry. Perl now not only makes it easier to use symbolic references to variables,\nbut also lets you have \"hard\" references to any piece of data or code. Any scalar may hold a\nhard reference. Because arrays and hashes contain scalars, you can now easily build arrays of\narrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and 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, the\nobject is destructed. See perlobj for more about objects. (In a sense, everything in Perl is an\nobject, but we usually reserve the word for references to objects that have been officially\n\"blessed\" into a class package.)\n\nSymbolic references are names of variables or other objects, just as a symbolic link in a Unix\nfilesystem contains merely the name of a file. The *glob notation is something of a symbolic\nreference. (Symbolic references are sometimes called \"soft references\", but please don't call\nthem 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 talking\nabout 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 always\nbehaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you\nhave 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\nBy using the backslash operator on a variable, subroutine, or value. (This works much like the &\n(address-of) operator in C.) This typically creates *another* reference to a variable, because\nthere's already a reference to the variable in the symbol table. But the symbol table reference\nmight go away, and you'll still have the reference that the backslash returned. Here are some\nexamples:\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 the\nbackslash operator. The most you can get is a reference to a typeglob, which is actually a\ncomplete symbol table entry. But see the explanation of the *foo{THING} syntax below. However,\nyou can still use type globs and globrefs as though they were IO handles.\n\nSquare Brackets\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 syntax\ndescribed later can be used to access this. For example, after the above, \"$arrayref->[2][1]\"\nwould have the value \"b\".)\n\nTaking a reference to an enumerated list is not the same as using square brackets--instead it's\nthe 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 (since\nthe keys are just strings rather than full-fledged scalars).\n\nCurly Brackets\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 complicated\na structure as you want. The multidimensional syntax described below works for these too. The\nvalues above are literals, but variables and expressions would work just as well, because\nassignment operators in Perl (even within local() or my()) are executable statements, not\ncompile-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 a\n\"return\" in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy\nand 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 have\nthese 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\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 not\nso much a declaration as it is an operator, like \"do{}\" or \"eval{}\". (However, no matter how\nmany times you execute that particular line (unless you're in an \"eval(\"...\")\"), $coderef will\nstill 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 says\nif you define an anonymous function in a particular lexical context, it pretends to run in that\ncontext 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 well\nas when you call it. It's useful for setting up little bits of code to run later, such as\ncallbacks. 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 closure is\nall about.\n\nThis applies only to lexical variables, by the way. Dynamic variables continue to work as they\nhave always worked. Closure is not something that most Perl programmers need trouble themselves\nabout to begin with.\n\nConstructors\nReferences are often returned by special subroutines called constructors. Perl objects are just\nreferences to a special type of object that happens to know which package it's associated with.\nConstructors are just special subroutines that know how to create that association. They do so\nby starting with an ordinary reference, and it remains an ordinary reference even while it's\nalso being an object. Constructors are often named \"new()\". You *can* 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 direct\nmethod 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\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\nA reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax.\n*foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which\nholds 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 IO\nhandle, used for file handles (\"open\" in perlfunc), sockets (\"socket\" in perlfunc and\n\"socketpair\" in perlfunc), and directory handles (\"opendir\" in perlfunc). For compatibility with\nprevious versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}, though it is discouraged,\nto encourage a consistent use of one name: IO. On perls between v5.8 and v5.22, it will issue a\ndeprecation 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 of\nscalars. *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used yet.\nThis 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 has\nbeen assigned to it. So, after \"*foo=*Foo::bar\", *foo will become \"*Foo::bar\" when used as a\nstring, 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 advantage is\nthat you have less risk of clobbering more than you want to with a typeglob assignment. (It\nstill conflates file and directory handles, though.) However, if you assign the incoming value\nto a scalar instead of a typeglob as we do in the examples below, there's no risk of that\nhappening.\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 references to\nget back to your long-lost data. There are several basic methods.\n\nSimple Scalar\nAnywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine\nname, you can replace the identifier with a simple scalar variable containing a reference of the\ncorrect 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 below.\nHowever, a \"simple scalar\" includes an identifier that itself uses method 1 recursively.\nTherefore, the following prints \"howdy\".\n\n$refrefref = \\\\\\\"howdy\";\nprint $$$$refrefref;\n\nBlock\nAnywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine\nname, you can replace the identifier with a BLOCK returning a reference of the correct type. In\nother 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 any\narbitrary 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 the\ncase. Consider the difference below; case 0 is a short-hand version of case 1, *not* case 2:\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 dereferencing\nthrough $hashref to the hash it's presumably referencing. That would be case 3.\n\nArrow Notation\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 so,\nit'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 we\ncan 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 the\nabove down to\n\n$array[$x]{\"foo\"}[0] = \"January\";\n\nWhich, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays\njust 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\nIf a reference happens to be a reference to an object, then there are probably methods to access\nthe things referred to, and you should probably stick to those methods unless you're in the\nclass package that defines the object's methods. In other words, be nice, and don't violate the\nobject's encapsulation without a very good reason. Perl does not enforce encapsulation. We are\nnot totalitarians here. We do expect some basic civility though.\n\nMiscellaneous Usage\nUsing a string or number as a reference produces a symbolic reference, as explained above. Using\na reference as a number produces an integer representing its storage location in memory. The\nonly useful thing to be done with this is to compare two references numerically to see whether\nthey 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 blessing\nas described in perlobj, as well as the numeric address expressed in hex. The ref() operator\nreturns just the type of thing the reference is pointing to, without the address. See \"ref\" in\nperlfunc 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 the\nsame 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 evaluated\nas a block. The block creates a reference to an anonymous array containing the results of the\ncall to \"mysub(1,2,3)\". So the whole block returns a reference to an array, which is then\ndereferenced by \"@{...}\" and stuck into the double-quoted string. This chicanery is also useful\nfor 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 \"${...}\".\nThus, 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 will\nnever be garbage-collected. This can lead to memory leaks.\n\nBecause objects in Perl are implemented as references, it's possible to have circular references\nwith objects as well. Imagine a TreeNode class where each node references its parent and child\nnodes. 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, it\nwill be garbage-collected. The next time you look at the value of the \"$foo->{bar}\" key, it will\nbe \"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, the\nlonger-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 didn't\nsay 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, the\nvalue 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. Lexical\nvariables (declared with my()) aren't in a symbol table, and thus are invisible to this\nmechanism. 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 all\n\"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 name\nfrom 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 a\nstring. 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 that\nfunction was compiled, creates a closure. It retains access to those variables even though it\ndoesn'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 similarly.\nSuppose you wanted functions named after the colors that generated HTML font changes for the\nvarious 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 a\ntypeglob 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(),"
                    },
                    {
                        "name": "blue",
                        "content": "less error-prone as well, since syntax checks happen at compile time. It's critical that any\nvariables in the anonymous subroutine be lexicals in order to create a proper closure. That's\nthe 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 you\nwanted to impose scalar context on the arguments of these functions (probably not a wise idea\nfor 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 late\nto be of much use. You could address this by putting the whole loop of assignments within a\nBEGIN block, forcing it to occur during compilation.\n\nAccess to lexicals that change over time--like those in the \"for\" loop above, basically aliases\nto elements from the surrounding lexical scopes-- only works with anonymous subs, not with named\nsubroutines. Generally said, named subroutines do not nest properly and should only be declared\nin 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 scope\nis entered a second time, its lexicals are created again, while the nested subs still reference\nthe 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 shared\"\ndue 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 the\nanonymous subroutine. But when it does, it has normal access to the lexical variable $x from the\nscope of outer() at the time outer is invoked.\n\nThis has the interesting effect of creating a function local to another function, something not\nnormally 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 is\nused.\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 worked,\nand should be entirely equivalent. This syntax allows dereferencing to be written and read\nentirely 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 the\nthing 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 warn\nby 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 context:\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\") will\nmake each element of the array an alias to the corresponding scalar referenced on the right-hand\nside:\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 forbidden\n(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 on\nthe 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 variables\nfrom an inner subroutine or \"eval\", the aliasing will only be visible within that inner sub, and\nwill not affect the outer subroutine where the variables are declared. This bizarre behavior is\nsubject 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 \"local\".\nThis syntax must be enabled with \"use feature 'declaredrefs'\". It is experimental, and will\nwarn by default unless \"no warnings 'experimental::refaliasing'\" is in effect.\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\nWARNING: Don't use references as hash keys\nYou may not (usefully) use a reference as the key to a hash. It will be converted into a string:\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 what\nyou'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 the\nuse of references can be found in the t/op/ref.t regression test in the Perl source directory.\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",
                "subsections": []
            }
        }
    }
}