http://www.perlmonks.org?node_id=1015174

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

Legacy code question: Suppose we have a script "S" which uses a number of modules "M1" ... "Mn". Furthermore suppose one of those module "Mi" exports its package global variable $foo. Can S determine the fully qualified name of $foo (in this case $Mi::foo)?

Re: How to de-reference a coderef? (B tricks) supplies a way to determine the fully qualified name of a sub from its coderef. Can something similar be done with variables?

Replies are listed 'Best First'.
Re: Can the fully qualified name of a global variable be determined?
by LanX (Saint) on Jan 24, 2013 at 14:44 UTC
    Since B::Deparse can do it, I suppose it's only a matter of how to access the optree and not if it's possible at all.

    lanx@nc10-ubuntu:~$ perl -MO=Deparse package TST; our $var; package main; print $var __END__ package TST; our $var; package main; print $TST::var;

    AT least this works w/o parsing all STASHes.

    Cheers Rolf

Re: Can the fully qualified name of a global variable be determined?
by LanX (Saint) on Jan 24, 2013 at 14:59 UTC
    OK it's a hack. but it works out-of-the box since B::Deparse is core! =)

    use B::Deparse; package TST; our $var; package main; $VARNAME='$var'; print B::Deparse->new()->coderef2text(eval "sub { $VARNAME }" );

    OUTPUT:

    { $TST::var; }

    And the rest is silence regex! :)

    Cheers Rolf

      UPDATE

      But I don't know if this helps with exported vars, since IIRC "exporting" means copying a reference into the importing namespace. In other words: the current "fully qualified name" is from the importing namespace.

      If you wanna find the original full qualified name you have to parse all loaded STASHes, till you find the reference. You can find the namespaces by inspecting %main::

      print join "\n", grep {/^.*::$/} keys %main::

      -->

      Tie:: utf8:: TST:: re:: DynaLoader:: mro:: strict:: Regexp:: Term:: UNIVERSAL:: overload:: Data:: IO:: Exporter:: Internals:: warnings:: Config:: DB:: CORE:: attributes:: Scalar:: vars:: XSLoader:: B:: main:: Carp:: PerlIO:: O:: bytes::

      UPDATE

      or by checking %INC

      Cheers Rolf

Re: Can the fully qualified name of a global variable be determined?
by vinoth.ree (Monsignor) on Jan 24, 2013 at 14:32 UTC

    Check with this module,Devel::Peek I guess it helps you.

Re: Can the fully qualified name of a global variable be determined?
by Anonymous Monk on Jan 24, 2013 at 14:35 UTC
Re: Can the fully qualified name of a global variable be determined?
by Khen1950fx (Canon) on Jan 25, 2013 at 20:04 UTC
    Symbol::Global::Name
    #!/usr/bin/perl -l use strict; use warnings; package Mi; our $foo = q{}; package S; use Symbol::Global::Name; print Symbol::Global::Name->find(\$foo);
Re: Can the fully qualified name of a global variable be determined?
by clueless newbie (Curate) on Jan 25, 2013 at 19:46 UTC