perlman gods <HR> <P> <H1><A NAME="NAME">NAME</A></H1> <P> perlref - Perl references and nested data structures <P> <HR> <H1><A NAME="DESCRIPTION">DESCRIPTION</A></H1> <P> Before release 5 of Perl it was difficult to represent complex data structures, because all references had to be symbolic--and even then it was difficult to refer to a variable instead of a symbol table entry. Perl now not only makes it easier to use symbolic references to variables, but also lets you have ``hard'' references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on. <P> Hard references are smart--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Note: the reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see [perlman:perlobj] for a detailed explanation.) If that thing happens to be an object, the object is destructed. See [perlman:perlobj|the perlobj manpage] for more about objects. (In a sense, everything in Perl is an object, but we usually reserve the word for references to objects that have been officially ``blessed'' into a class package.) <P> Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The [perlfunc:glob] notation is a kind of symbolic reference. (Symbolic references are sometimes called ``soft references'', but please don't call them that; references are confusing enough without useless synonyms.) <P> In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word ``reference'' is used without an adjective, as in the following paragraph, it is usually talking about a hard reference. <P> References are easy to use in Perl. There is just one overriding principle: Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it. <P> <HR> <H2><A NAME="Making_References">Making References</A></H2> <P> References can be created in several ways. <OL> <LI><STRONG><A NAME="item__">.</A></STRONG> <P> By using the backslash operator on a variable, subroutine, or value. (This works much like the &amp; (address-of) operator in <FONT SIZE=-1>C.)</FONT> Note that this typically creates <EM>ANOTHER</EM> reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples: <P> <PRE> $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&amp;handler; $globref = \*foo; </PRE> <P> It isn't possible to create a true reference to an <FONT SIZE=-1>IO</FONT> handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the <CODE>*foo{THING}</CODE> syntax below. However, you can still use type globs and globrefs as though they were <FONT SIZE=-1>IO</FONT> handles. <P><LI><STRONG>.</STRONG> <FONT SIZE=-1>A</FONT> reference to an anonymous array can be created using square brackets: <P> <PRE> $arrayref = &#091;1, 2, &#091;'a', 'b', 'c'&#093;&#093;; </PRE> <P> Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, <CODE>$arrayref-&gt;&#091;2&#093;&#091;1&#093;</CODE> would have the value ``b''.) <P> Note that taking a reference to an enumerated list is not the same as using square brackets--instead it's the same as creating a list of references! <P> <PRE> @list = (\$a, \@b, \%c); @list = \($a, @b, %c); # same thing! </PRE> <P> As a special case, <CODE>\(@foo)</CODE> returns a list of references to the contents of <CODE>@foo</CODE>, not a reference to <CODE>@foo</CODE> itself. Likewise for <CODE>%foo</CODE>. <P><LI><STRONG>.</STRONG> <FONT SIZE=-1>A</FONT> reference to an anonymous hash can be created using curly brackets: <P> <PRE> $hashref = { 'Adam' =&gt; 'Eve', 'Clyde' =&gt; 'Bonnie', }; </PRE> <P> Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within <CODE>local()</CODE> or <CODE>my())</CODE> are executable statements, not compile-time declarations. <P> Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a <CODE>+</CODE> or a [perlfunc:return|return] in front so that Perl realizes the opening brace isn't starting a <FONT SIZE=-1>BLOCK.</FONT> The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle. <P> For example, if you wanted a function to make a new hash and return a reference to it, you have these options: <P> <PRE> sub hashem { { @_ } } # silently wrong sub hashem { +{ @_ } } # ok sub hashem { return { @_ } } # ok </PRE> <P> On the other hand, if you want the other meaning, you can do this: <P> <PRE> sub showem { { @_ } } # ambiguous (currently ok, but may change) sub showem { {; @_ } } # ok sub showem { { return @_ } } # ok </PRE> <P> Note how the leading <CODE>+{</CODE> and <CODE>{;</CODE> always serve to disambiguate the expression to mean either the <FONT SIZE=-1>HASH</FONT> reference, or the <FONT SIZE=-1>BLOCK.</FONT> <P><LI><STRONG>.</STRONG> <FONT SIZE=-1>A</FONT> reference to an anonymous subroutine can be created by using [perlfunc:sub|sub] without a subname: <P> <PRE> $coderef = sub { print &quot;Boink!\n&quot; }; </PRE> <P> Note the presence of the semicolon. Except for the fact that the code inside isn't executed immediately, a [perlfunc:sub] is not so much a declaration as it is an operator, like [perlfunc:do] or [perlfunc:eval]. (However, no matter how many times you execute that particular line (unless you're in an [perlfunc:eval|eval(&quot;...&quot;)]), <CODE>$coderef</CODE> will still have a reference to the <EM>SAME</EM> anonymous subroutine.) <P> Anonymous subroutines act as closures with respect to <CODE>my()</CODE> variables, that is, variables visible lexically within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside of the context. <P> In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see [perlman:perlobj|the perlobj manpage]. <P> You can also think of closure as a way to write a subroutine template without using eval. (In fact, in version 5.000, eval was the <EM>only</EM> way to get closures. You may wish to use ``require 5.001'' if you use closures.) <P> Here's a small example of how closures works: <P> <PRE> sub newprint { my $x = shift; return sub { my $y = shift; print &quot;$x, $y!\n&quot;; }; } $h = newprint(&quot;Howdy&quot;); $g = newprint(&quot;Greetings&quot;); </PRE> <P> <PRE> # Time passes... </PRE> <P> <PRE> &amp;$h(&quot;world&quot;); &amp;$g(&quot;earthlings&quot;); </PRE> <P> This prints <P> <PRE> Howdy, world! Greetings, earthlings! </PRE> <P> Note particularly that <CODE>$x</CODE> continues to refer to the value passed into <CODE>newprint()</CODE> <EM>despite</EM> the fact that the ``my $x'' has seemingly gone out of scope by the time the anonymous subroutine runs. That's what closure is all about. <P> This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with. <P><LI><STRONG>.</STRONG> References are often returned by special subroutines called constructors. Perl objects are just references to a special kind of object that happens to know which package it's associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it's also being an object. Constructors are often named <CODE>new()</CODE> and called indirectly: <P> <PRE> $objref = new Doggie (Tail =&gt; 'short', Ears =&gt; 'long'); </PRE> <P> But don't have to be: <P> <PRE> $objref = Doggie-&gt;new(Tail =&gt; 'short', Ears =&gt; 'long'); </PRE> <P> <PRE> use Term::Cap; $terminal = Term::Cap-&gt;Tgetent( { OSPEED =&gt; 9600 }); </PRE> <P> <PRE> use Tk; $main = MainWindow-&gt;new(); $menubar = $main-&gt;Frame(-relief =&gt; &quot;raised&quot;, -borderwidth =&gt; 2) </PRE> <LI><STRONG>.</STRONG> <P> References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet. <P><LI><STRONG>.</STRONG> <FONT SIZE=-1>A</FONT> reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the <FONT SIZE=-1>THING</FONT> slot in <CODE>*foo</CODE> (which is the symbol table entry which holds everything known as foo). <P> <PRE> $scalarref = *foo{SCALAR}; $arrayref = *ARGV{ARRAY}; $hashref = *ENV{HASH}; $coderef = *handler{CODE}; $ioref = *STDIN{IO}; $globref = *foo{GLOB}; </PRE> <P> All of these are self-explanatory except for *foo{IO}. It returns the <FONT SIZE=-1>IO</FONT> handle, used for file handles ([perlfunc:open|open]), sockets ([perlfunc:socket|socket] and [perlfunc:socketpair|socketpair]), and directory handles ([perlfunc:opendir|opendir]). For compatibility with previous versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}. <P> *foo{THING} returns undef if that particular <FONT SIZE=-1>THING</FONT> hasn't been used yet, except in the case of scalars. *foo{SCALAR} returns a reference to an anonymous scalar if <CODE>$foo</CODE> hasn't been used yet. This might change in a future release. <P> *foo{IO} is an alternative to the <FONT SIZE=-1>\*HANDLE</FONT> mechanism given in [perlman:perldata] for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won't create a new filehandle for you. Its advantage is that you have no risk of clobbering more than you want to with a typeglob assignment, although if you assign to a scalar instead of a typeglob, you're ok. <P> <PRE> splutter(*STDOUT); splutter(*STDOUT{IO}); </PRE> <P> <PRE> sub splutter { my $fh = shift; print $fh &quot;her um well a hmmm\n&quot;; } </PRE> <P> <PRE> $rec = get_rec(*STDIN); $rec = get_rec(*STDIN{IO}); </PRE> <P> <PRE> sub get_rec { my $fh = shift; return scalar &lt;$fh&gt;; } </PRE> </OL> <P> <HR> <H2><A NAME="Using_References">Using References</A></H2> <P> That's it for creating references. By now you're probably dying to know how to use references to get back to your long-lost data. There are several basic methods. <OL> <LI><STRONG>.</STRONG> <P> Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type: <P> <PRE> $bar = $$scalarref; push(@$arrayref, $filename); $$arrayref&#091;0&#093; = &quot;January&quot;; $$hashref{&quot;KEY&quot;} = &quot;VALUE&quot;; &amp;$coderef(1,2,3); print $globref &quot;output\n&quot;; </PRE> <P> It's important to understand that we are specifically <EM>NOT</EM> dereferencing <CODE>$arrayref&#091;0&#093;</CODE> or <CODE>$hashref{&quot;KEY&quot;}</CODE> there. The dereference of the scalar variable happens <EM>BEFORE</EM> it does any key lookups. Anything more complicated than a simple scalar variable must use methods 2 or 3 below. However, a ``simple scalar'' includes an identifier that itself uses method 1 recursively. Therefore, the following prints ``howdy''. <P> <PRE> $refrefref = \\\&quot;howdy&quot;; print $$$$refrefref; </PRE> <LI><STRONG>.</STRONG> <P> Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a <FONT SIZE=-1>BLOCK</FONT> returning a reference of the correct type. In other words, the previous examples could be written like this: <P> <PRE> $bar = ${$scalarref}; push(@{$arrayref}, $filename); ${$arrayref}&#091;0&#093; = &quot;January&quot;; ${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;; &amp;{$coderef}(1,2,3); $globref-&gt;print(&quot;output\n&quot;); # iff IO::Handle is loaded </PRE> <P> Admittedly, it's a little silly to use the curlies in this case, but the <FONT SIZE=-1>BLOCK</FONT> can contain any arbitrary expression, in particular, subscripted expressions: <P> <PRE> &amp;{ $dispatch{$index} }(1,2,3); # call correct routine </PRE> <P> Because of being able to omit the curlies for the simple case of <CODE>$$x</CODE>, people often make the mistake of viewing the dereferencing symbols as proper operators, and wonder about their precedence. If they were, though, you could use parentheses instead of braces. That's not the case. Consider the difference below; case 0 is a short-hand version of case 1, <EM>NOT</EM> case 2: <P> <PRE> $$hashref{&quot;KEY&quot;} = &quot;VALUE&quot;; # CASE 0 ${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;; # CASE 1 ${$hashref{&quot;KEY&quot;}} = &quot;VALUE&quot;; # CASE 2 ${$hashref-&gt;{&quot;KEY&quot;}} = &quot;VALUE&quot;; # CASE 3 </PRE> <P> Case 2 is also deceptive in that you're accessing a variable called %hashref, not dereferencing through <CODE>$hashref</CODE> to the hash it's presumably referencing. That would be case 3. <P><LI><STRONG>.</STRONG> Subroutine calls and lookups of individual array elements arise often enough that it gets cumbersome to use method 2. As a form of syntactic sugar, the examples for method 2 may be written: <P> <PRE> $arrayref-&gt;&#091;0&#093; = &quot;January&quot;; # Array element $hashref-&gt;{&quot;KEY&quot;} = &quot;VALUE&quot;; # Hash element $coderef-&gt;(1,2,3); # Subroutine call </PRE> <P> The left side of the arrow can be any expression returning a reference, including a previous dereference. Note that <CODE>$array&#091;$x&#093;</CODE> is <EM>NOT</EM> the same thing as <CODE>$array-&gt;&#091;$x&#093;</CODE> here: <P> <PRE> $array&#091;$x&#093;-&gt;{&quot;foo&quot;}-&gt;&#091;0&#093; = &quot;January&quot;; </PRE> <P> This is one of the cases we mentioned earlier in which references could spring into existence when in an lvalue context. Before this statement, <CODE>$array&#091;$x&#093;</CODE> may have been undefined. If so, it's automatically defined with a hash reference so that we can look up <CODE>{&quot;foo&quot;}</CODE> in it. Likewise <CODE>$array&#091;$x&#093;-&gt;{&quot;foo&quot;}</CODE> will automatically get defined with an array reference so that we can look up <CODE>&#091;0&#093;</CODE> in it. This process is called <EM>autovivification</EM>. <P> One more thing here. The arrow is optional <EM>BETWEEN</EM> brackets subscripts, so you can shrink the above down to <P> <PRE> $array&#091;$x&#093;{&quot;foo&quot;}&#091;0&#093; = &quot;January&quot;; </PRE> <P> Which, in the degenerate case of using only ordinary arrays, gives you multidimensional arrays just like C's: <P> <PRE> $score&#091;$x&#093;&#091;$y&#093;&#091;$z&#093; += 42; </PRE> <P> Well, okay, not entirely like C's arrays, actually. <FONT SIZE=-1>C</FONT> doesn't know how to grow its arrays on demand. Perl does. <P><LI><STRONG>.</STRONG> If a reference happens to be a reference to an object, then there are probably methods to access the things referred to, and you should probably stick to those methods unless you're in the class package that defines the object's methods. In other words, be nice, and don't violate the object's encapsulation without a very good reason. Perl does not enforce encapsulation. We are not totalitarians here. We do expect some basic civility though. </OL> <P> The <CODE>ref()</CODE> operator may be used to determine what type of thing the reference is pointing to. See [perlman:perlfunc|the perlfunc manpage]. <P> The <CODE>bless()</CODE> operator may be used to associate the object a reference points to with a package functioning as an object class. See [perlman:perlobj|the perlobj manpage]. <P> <FONT SIZE=-1>A</FONT> typeglob may be dereferenced the same way a reference can, because the dereference syntax always indicates the kind of reference desired. So <CODE>${*foo}</CODE> and <CODE>${\$foo}</CODE> both indicate the same scalar variable. <P> Here's a trick for interpolating a subroutine call into a string: <P> <PRE> print &quot;My sub returned @{&#091;mysub(1,2,3)&#093;} that time.\n&quot;; </PRE> <P> The way it works is that when the <CODE>@{...}</CODE> is seen in the double-quoted string, it's evaluated as a block. The block creates a reference to an anonymous array containing the results of the call to <CODE>mysub(1,2,3)</CODE>. So the whole block returns a reference to an array, which is then dereferenced by <CODE>@{...}</CODE> and stuck into the double-quoted string. This chicanery is also useful for arbitrary expressions: <P> <PRE> print &quot;That yields @{&#091;$n + 5&#093;} widgets\n&quot;; </PRE> <P> <HR> <H2><A NAME="Symbolic_references">Symbolic references</A></H2> <P> We said that references spring into existence as necessary if they are undefined, but we didn't say what happens if a value used as a reference is already defined, but <EM>ISN'T</EM> a hard reference. If you use it as a reference in this case, it'll be treated as a symbolic reference. That is, the value of the scalar is taken to be the <EM>NAME</EM> of a variable, rather than a direct link to a (possibly) anonymous value. <P> People frequently expect it to work like this. So it does. <P> <PRE> $name = &quot;foo&quot;; $$name = 1; # Sets $foo ${$name} = 2; # Sets $foo ${$name x 2} = 3; # Sets $foofoo $name-&gt;&#091;0&#093; = 4; # Sets $foo&#091;0&#093; @$name = (); # Clears @foo &amp;$name(); # Calls &amp;foo() (as in Perl 4) $pack = &quot;THAT&quot;; ${&quot;${pack}::$name&quot;} = 5; # Sets $THAT::foo without eval </PRE> <P> This is very powerful, and slightly dangerous, in that it's possible to intend (with the utmost sincerity) to use a hard reference, and accidentally use a symbolic reference instead. To protect against that, you can say <P> <PRE> use strict 'refs'; </PRE> <P> and then only hard references will be allowed for the rest of the enclosing block. An inner block may countermand that with <P> <PRE> no strict 'refs'; </PRE> <P> Only package variables (globals, even if localized) are visible to symbolic references. Lexical variables (declared with <CODE>my())</CODE> aren't in a symbol table, and thus are invisible to this mechanism. For example: <P> <PRE> local $value = 10; $ref = \$value; { my $value = 20; print $$ref; } </PRE> <P> This will still print 10, not 20. Remember that <CODE>local()</CODE> affects package variables, which are all ``global'' to the package. <P> <HR> <H2><A NAME="Not_so_symbolic_references">Not-so-symbolic references</A></H2> <P> <FONT SIZE=-1>A</FONT> new feature contributing to readability in perl version 5.001 is that the brackets around a symbolic reference behave more like quotes, just as they always have within a string. That is, <P> <PRE> $push = &quot;pop on &quot;; print &quot;${push}over&quot;; </PRE> <P> has always meant to print ``pop on over'', despite the fact that push is a reserved word. This has been generalized to work the same outside of quotes, so that <P> <PRE> print ${push} . &quot;over&quot;; </PRE> <P> and even <P> <PRE> print ${ push } . &quot;over&quot;; </PRE> <P> will have the same effect. (This would have been a syntax error in Perl 5.000, though Perl 4 allowed it in the spaceless form.) Note that this construct is <EM>not</EM> considered to be a symbolic reference when you're using strict refs: <P> <PRE> use strict 'refs'; ${ bareword }; # Okay, means $bareword. ${ &quot;bareword&quot; }; # Error, symbolic reference. </PRE> <P> Similarly, because of all the subscripting that is done using single words, we've applied the same rule to any bareword that is used for subscripting a hash. So now, instead of writing <P> <PRE> $array{ &quot;aaa&quot; }{ &quot;bbb&quot; }{ &quot;ccc&quot; } </PRE> <P> you can write just <P> <PRE> $array{ aaa }{ bbb }{ ccc } </PRE> <P> and not worry about whether the subscripts are reserved words. In the rare event that you do wish to do something like <P> <PRE> $array{ shift } </PRE> <P> you can force interpretation as a reserved word by adding anything that makes it more than a bareword: <P> <PRE> $array{ shift() } $array{ +shift } $array{ shift @_ } </PRE> <P> The <STRONG>-w</STRONG> switch will warn you if it interprets a reserved word as a string. But it will no longer warn you about using lowercase words, because the string is effectively quoted. <P> <HR> <H2><A NAME="Pseudo_hashes_Using_an_array_as">Pseudo-hashes: Using an array as a hash</A></H2> <P> <FONT SIZE=-1>WARNING:</FONT> This section describes an experimental feature. Details may change without notice in future versions. <P> Beginning with release 5.005 of Perl you can use an array reference in some contexts that would normally require a hash reference. This allows you to access array elements using symbolic names, as if they were fields in a structure. <P> For this to work, the array must contain extra information. The first element of the array has to be a hash reference that maps field names to array indices. Here is an example: <P> <PRE> $struct = &#091;{foo =&gt; 1, bar =&gt; 2}, &quot;FOO&quot;, &quot;BAR&quot;&#093;; </PRE> <P> <PRE> $struct-&gt;{foo}; # same as $struct-&gt;&#091;1&#093;, i.e. &quot;FOO&quot; $struct-&gt;{bar}; # same as $struct-&gt;&#091;2&#093;, i.e. &quot;BAR&quot; </PRE> <P> <PRE> keys %$struct; # will return (&quot;foo&quot;, &quot;bar&quot;) in some order values %$struct; # will return (&quot;FOO&quot;, &quot;BAR&quot;) in same some order </PRE> <P> <PRE> while (my($k,$v) = each %$struct) { print &quot;$k =&gt; $v\n&quot;; } </PRE> <P> Perl will raise an exception if you try to delete keys from a pseudo-hash or try to access nonexistent fields. For better performance, Perl can also do the translation from field names to array indices at compile time for typed object references. See <U>the fields manpage</U><!--../lib/fields.html-->. <P> <HR> <H2><A NAME="Function_Templates">Function Templates</A></H2> <P> As explained above, a closure is an anonymous function with access to the lexical variables visible when that function was compiled. It retains access to those variables even though it doesn't get run until later, such as in a signal handler or a Tk callback. <P> Using a closure as a function template allows us to generate many functions that act similarly. Suppopose you wanted functions named after the colors that generated <FONT SIZE=-1>HTML</FONT> font changes for the various colors: <P> <PRE> print &quot;Be &quot;, red(&quot;careful&quot;), &quot;with that &quot;, green(&quot;light&quot;); </PRE> <P> The <CODE>red()</CODE> and <CODE>green()</CODE> functions would be very similar. To create these, we'll assign a closure to a typeglob of the name of the function we're trying to build. <P> <PRE> @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict 'refs'; # allow symbol table manipulation *$name = *{uc $name} = sub { &quot;&lt;FONT COLOR='$name'&gt;@_&lt;/FONT&gt;&quot; }; } </PRE> <P> Now all those different functions appear to exist independently. You can call <CODE>red(),</CODE> <CODE>RED(),</CODE> <CODE>blue(),</CODE> <CODE>BLUE(),</CODE> <CODE>green(),</CODE> etc. This technique saves on both compile time and memory use, and is less error-prone as well, since syntax checks happen at compile time. It's critical that any variables in the anonymous subroutine be lexicals in order to create a proper closure. That's the reasons for the [perlfunc:my|my] on the loop iteration variable. <P> This is one of the only places where giving a prototype to a closure makes much sense. If you wanted to impose scalar context on the arguments of these functions (probably not a wise idea for this particular example), you could have written it this way instead: <P> <PRE> *$name = sub ($) { &quot;&lt;FONT COLOR='$name'&gt;$_&#091;0&#093;&lt;/FONT&gt;&quot; }; </PRE> <P> However, since prototype checking happens at compile time, the assignment above happens too late to be of much use. You could address this by putting the whole loop of assignments within a <FONT SIZE=-1>BEGIN</FONT> block, forcing it to occur during compilation. <P> Access to lexicals that change over type--like those in the <CODE>for</CODE> loop above--only works with closures, not general subroutines. In the general case, then, named subroutines do not nest properly, although anonymous ones do. If you are accustomed to using nested subroutines in other programming languages with their own private variables, you'll have to work at it a bit in Perl. The intuitive coding of this kind of thing incurs mysterious warnings about ``will not stay shared''. For example, this won't work: <P> <PRE> sub outer { my $x = $_&#091;0&#093; + 35; sub inner { return $x * 19 } # WRONG return $x + inner(); } </PRE> <P> <FONT SIZE=-1>A</FONT> work-around is the following: <P> <PRE> sub outer { my $x = $_&#091;0&#093; + 35; local *inner = sub { return $x * 19 }; return $x + inner(); } </PRE> <P> Now <CODE>inner()</CODE> can only be called from within <CODE>outer(),</CODE> because of the temporary assignments of the closure (anonymous subroutine). But when it does, it has normal access to the lexical variable <CODE>$x</CODE> from the scope of <CODE>outer().</CODE> <P> This has the interesting effect of creating a function local to another function, something not normally supported in Perl. <P> <HR> <H1><A NAME="WARNING">WARNING</A></H1> <P> You may not (usefully) use a reference as the key to a hash. It will be converted into a string: <P> <PRE> $x{ \$a } = $a; </PRE> <P> If you try to dereference the key, it won't do a hard dereference, and you won't accomplish what you're attempting. You might want to do something more like <P> <PRE> $r = \@a; $x{ $r } = $r; </PRE> <P> And then at least you can use the <CODE>values(),</CODE> which will be real refs, instead of the <CODE>keys(),</CODE> which won't. <P> The standard Tie::RefHash module provides a convenient workaround to this. <P> <HR> <H1><A NAME="SEE_ALSO">SEE ALSO</A></H1> <P> Besides the obvious documents, source code can be instructive. Some rather pathological examples of the use of references can be found in the <EM>t/op/ref.t</EM> regression test in the Perl source directory. <P> See also [perlman:perldsc|the perldsc manpage] and [perlman:perllol|the perllol manpage] for how to use references to create complex data structures, and [perlman:perltoot|the perltoot manpage], [perlman:perlobj|the perlobj manpage], and [perlman:perlbot|the perlbot manpage] for how to use them to create objects. <HR> <BR>Return to the [Library]<BR>