title: Shared variables in the context of subroutines vs anonymous subroutines
body: <p>I saw this bit of code in an answer to another post: <a href="https://stackoverflow.com/questions/834590/why-would-i-use-perl-anonymous-subroutines-instead-of-a-named-one">Why would I use Perl anonymous subroutines instead of a named one?</a>, but couldn't figure out exactly what as going on, so I wanted to run it myself. </p>
  
  <pre><code>sub outer
  {
    my $a = 123;
  
    sub inner
    {
      print $a, "\n"; #line 15 (for your reference, all other comments are the OP's)
    }
  
    # At this point, $a is 123, so this call should always print 123, right?
    inner();
  
    $a = 456;
  }
  
  outer(); # prints 123
  outer(); # prints 456! Surprise!
  </code></pre>
  
  <p>In the above example, I received a warning: "Variable $a will not stay shared at line 15.
  Obviously, this is why the output is "unexpected," but I still don't really understand what's happening here. </p>
  
  <pre><code>sub outer2
  {
    my $a = 123;
  
    my $inner = sub
    {
      print $a, "\n";
    };
  
    # At this point, $a is 123, and since the anonymous subrotine 
    # whose reference is stored in $inner closes over $a in the 
    # "expected" way...
    $inner-&gt;();
  
    $a = 456;
  }
  
  # ...we see the "expected" results
  outer2(); # prints 123
  outer2(); # prints 123
  </code></pre>
  
  <p>In the same vein, I don't understand what's happening in this example either.  Could someone please explain?</p>
  
  <p>Thanks in advance.</p>