Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Accessing lexically scoped variables from a subref

by chromatic (Archbishop)
on Dec 28, 2007 at 00:23 UTC ( [id://659277]=note: print w/replies, xml ) Need Help??


in reply to Accessing lexically scoped variables from a subref

ISBN 0596526741 Perl Hacks #76 recommends the use of PadWalker, such that you can write something like:

package Foo; use PadWalker 'closed_over'; sub convert { my ($package, $sub) = @_; my $vars = closed_over( $sub ); return join ', ', map { "$_ => $vars->{$_}" } keys %$vars; }

Replies are listed 'Best First'.
Re^2: Accessing lexically scoped variables from a subref
by /dev/urandom (Beadle) on Dec 28, 2007 at 01:26 UTC
    This is indeed an excellent solution. The only problem is that it's not a pure perl module. However, after looking at the xs, the actual code for the closed_over function is rather small. For a simple subref:
    $i = 12; $a = sub { $i };
    All it took to get $i was this:
    B::svref_2object($a)->PADLIST->ARRAYelt(1)->ARRAYelt(1)->SV->object_2s +vref
    The only problem with using this is that I have no idea how it actually works. I just assumed that PADLIST contains all the local variables for that reference, but why the two-dimensional AV after that? Or for that matter, why is $i located on the second position of the second array? The others just return a B::SPECIAL, which I have no idea what its purpose is.
      The only problem with using this is that I have no idea how it actually works. I just assumed that PADLIST contains all the local variables for that reference, but why the two-dimensional AV after that?

      Short answer: the first array holds the names, the second holds the values.

      Longer answer:

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://659277]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-19 03:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found