Perhaps I'm being too simple-minded, but please consider this variant:
use strict qw(vars subs); my $name; { my $name = 'red'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; } { my $name = 'blue'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; } $name = '<none>'; print red(), "\n"; print blue(), "\n"; __END__ <FONT COLOR='red'></FONT> <FONT COLOR='blue'></FONT>
Without the additional block delimiters ({}) and my declarations, the variable $name indeed always refers to the same storage (which, I admit, was not clear in my own mind when I wrote the above comment). Closures (red() and blue() here) only get a copy of a portion of their lexical environment (that is, become "closures", properly so-called) when they escape a region where that portion is (lexically, of course) in scope. Without a block that the thread of execution leaves, no closure is created and the code is indistinguishable from a regular sub. Note that red() and blue() (i.e. &red and &blue) exist outside the blocks because they are created in the package's (here, main) symbol table -- as using a type glob (*) always implies. Here's the code with another wrinkle to illustrate:
use strict qw(vars subs); { my $name; { my $name = 'red'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; } { my $name = 'blue'; *$name = sub { "<FONT COLOR='$name'>@_</FONT>" }; } *foo = sub { print red($name), "\n"; print blue($name), "\n"; }; $name = 'another wrinkle'; } foo(); print red('hi mom'); __END__ <FONT COLOR='red'>another wrinkle</FONT> <FONT COLOR='blue'>another wrinkle</FONT> <FONT COLOR='red'>hi mom</FONT>

In reply to Re^3: How do closures and variable scope (my,our,local) interact in perl? by Zarchne
in thread How do closures and variable scope (my,our,local) interact in perl? by ELISHEVA

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.