LanX has asked for the wisdom of the Perl Monks concerning the following question:

Hi

PadWalker has a handy function peek_sub() to identify all private vars in a sub, but lacks a method to do so with package vars.

DB<318> $code = sub { my $a ** $b ** $bla::c } DB<319> x peek_sub($code) 0 HASH(0x3d161a8) '$a' => SCALAR(0x3d18da0) -> undef DB<320>

What's the best way to achieve this, except parsing the text output of B::Concise for GVs? (is this even reliable?) °

I think I asked this before, but who knows what changed in the meantime :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

UPDATE

°) #<-- comments added

D:\>perl -MO=Concise,bla -e "sub bla {@a = ($b, my $c)}" main::bla: 9 <1> leavesub[1 ref] K/REFC,1 ->(end) - <@> lineseq KP ->9 1 <;> nextstate(main 2 -e:1) v ->2 8 <2> aassign[t5] KS/COM_AGG ->9 - <1> ex-list lKP ->5 2 <0> pushmark s ->3 - <1> ex-rv2sv sK/1 ->4 3 <#> gvsv[*b] s ->4 #<-- $::b 4 <0> padsv[$c:2,3] sM/LVINTRO ->5 #<-- my $c - <1> ex-list lK ->8 5 <0> pushmark s ->6 7 <1> rv2av[t2] lKRM*/1 ->8 6 <#> gv[*a] s ->7 #<-- @::a -e syntax OK

Replies are listed 'Best First'.
Re: Inspecting package vars in a sub
by choroba (Cardinal) on Dec 04, 2020 at 22:18 UTC
    Why do you need it?

    I'm just curious. Also, I probably asked this before, but who knows what changed in the meantime :-)

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Long story, ... you know meta-programming and syntactic sugar stuff. ;)

      For instance I want to be able to automatically localize special package vars in a code-block

      sub xsub (&) { my ($code)=@_; sub { local ($a,$b) = @_; &$code; } } my $c_ref = xsub { $a ** $b }; say $c_ref->(2,3); #> 8

      This looks better than sub { $_[0] ** $_[1] }

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery