Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

get name of lexical variable

by khwilliamson (Initiate)
on Jul 12, 2009 at 17:14 UTC ( #779385=perlquestion: print w/replies, xml ) Need Help??
khwilliamson has asked for the wisdom of the Perl Monks concerning the following question:

I have a subroutine which is passed a reference to a lexical variable like foo(\$lex). Is there a way to find the string 'lex' in that subroutine? Thanks in advance

Replies are listed 'Best First'.
Re: get name of lexical variable
by moritz (Cardinal) on Jul 12, 2009 at 17:46 UTC

    Just an idea, don't know if it might work:

    You could use PadWalker to sniff your caller's lexicals and see if the reference address of any of them is equal to the reference you've got.

      PadWalker provides a var_name function that takes the reference and does that for you. It's even more reliable than looping over the lexicals, when the lexical you want is hidden:
      #!/usr/bin/perl -l use strict; use warnings; use PadWalker ":all"; sub foo { my $x; for ($x) { my $x; bar(\$_); } } sub bar { print var_name(1, $_[0]); # works my $vars = peek_my(1); print grep $vars->{$_} == $_[0], keys %$vars; # doesn't work unle +ss 2nd my $x is commented out } foo();
Re: get name of lexical variable
by psini (Deacon) on Jul 12, 2009 at 17:41 UTC

    Dunno, but it makes little sense to me. For you can have an anonymous reference. (no name) or you can have a reference to a scalar that has more than one name (using Scalar::Alias or similar)

    So the question "which is the name of the var referenced by $x" may have zero, one or more than one answer.

    Is yours an academic question or have you a specific need in mind? Maybe it is an XY Problem.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

Re: get name of lexical variable
by mzedeler (Pilgrim) on Jul 12, 2009 at 20:30 UTC

    If you need that information, you are breaking a number of encapsulation rules that are really bad to break.

    Could you explain why you want to do this in the first place?

      One could write a nice subroutine useful in debugging, whic when called in the following way:

      my $aLex=25; print(display($aLex),"\n");
      would print
      $aLex == 25

      Ronald Fischer <>

        I agree that there are uses for a subroutine that can return such names as requested, but usually when people ask for something like this, its a sign of a more mundane problem solved in the wrong way.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://779385]
Front-paged by Arunbear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2017-05-25 02:56 GMT
Find Nodes?
    Voting Booth?