in reply to Re: Accessing lexicals in other scopes dynamically by name
in thread Accessing lexicals in other scopes dynamically by name

> Note: Subs only capture variables it knows it will need.

I ran some tests, IMHO thats not right, the point is rather that at run time the variable doesn't exist any more in your example.

Since it's only referenced by symbol, there is no reference count on the variable and the garbage collector already deleted it.

Cheers Rolf

  • Comment on Re^2: Accessing lexicals in other scopes dynamically by name

Replies are listed 'Best First'.
Re^3: Accessing lexicals in other scopes dynamically by name
by ikegami (Patriarch) on Jul 30, 2010 at 22:35 UTC

    the point is rather that at run time the variable doesn't exist any more in your example.

    Exactly. And the reason it doesn't exist is because it wasn't captured. That would have kept it alive. You can see the capture increasing the ref count in the following snippet:

    $ perl -MDevel::Peek -e' sub f { my $x; Dump($x); my @a = map { sub { $x } } 1..3; Dump($x); } f() ' SV = NULL(0x0) at 0x817bc90 REFCNT = 1 FLAGS = (PADMY) SV = NULL(0x0) at 0x817bc90 REFCNT = 4 FLAGS = (PADMY)
Re^3: Accessing lexicals in other scopes dynamically by name
by morgon (Priest) on Jul 30, 2010 at 17:52 UTC
    I think ikegami is right after all.

    Consider:

    use strict; { my $a = \$a; print "a=$a\n"; sub f { my $var = shift; print $var, "=", eval "\$$var", "\n"; }; } &f("a");

    $a references itself, so it will never be garbage-collected, yet it is not accessible in the eval.

      Indeed it has nothing (or little) to do with garbage collection.

      IMHO it's the dynamic scope (i.e. the scope local has), eval can access the surrounding lexpads of f's closure only as long as there is a call chain connecting them, because the "capture" of $a is missing!

      use strict; { my $a = \$a; print "a=$a\n"; sub f { my $var = shift; print $var, "=", eval "\$$var", "\n"; }; i(); # works } #&f("a"); sub g { f("a") } sub h { g() } sub i { h() }

      Cheers Rolf