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

In a subroutine, how can I get the name of the typeglob to which the scalar that was passed in belongs to?
tellme_my_typeglob $x; # should output 'x'

Replies are listed 'Best First'.
Re: How does one get the name of a passed scalar?
by japhy (Canon) on May 23, 2001 at 22:37 UTC
(tye)Re: How does one get the name of a passed scalar?
by tye (Sage) on May 24, 2001 at 09:06 UTC

    Ah, the best I could come up with for that was an editor macro that inserts: print "$_=(".eval($_).")\n" for qw( ); and then you type any variable names you like into the qw() part.

    BTW, you can't just make this a Perl function as most variables of most worth-while programs won't be available for the subroutine to access by using eval on their name.

    Also, if you want this to work for arrays as well: print "$_=(".eval(qq("$_")).")\n" for qw( ); and if you want this to work for hashes and other types of expressions: print "$_=(".join(",",eval$_).")\n" for qw( ); so I'd probably just use that last one.

            - tye (but my friends call me "Tye")
Re: How does one get the name of a passed scalar?
by merlyn (Sage) on May 24, 2001 at 00:12 UTC
    You can't, in general. What would it do with this:
    tellme_my_typeglob ${ \42 }; # should output... what?
    What problem are you trying to solve, the solution of which involved solving this problem? Because I think you'll have to back up a step.

    -- Randal L. Schwartz, Perl hacker

Re: How does one get the name of a passed scalar?
by Dr. Mu (Hermit) on May 24, 2001 at 07:57 UTC
    Why don't you go about it the other way? Pass the name of the variable and use eval to get its value:
    $test = 123; echoprint('$test'); sub echoprint { print "$_[0] = ".eval($_[0]) }
    Just don't forget to use single quotes when you call eshoprint!
Re: How does one get the name of a passed scalar?
by princepawn (Parson) on May 23, 2001 at 22:54 UTC
    maybe a source filter of some sort? Ie, Filter::Simple might be the way to go.
Re: How does one get the name of a passed scalar?
by princepawn (Parson) on May 24, 2001 at 01:19 UTC
    I'm just sick of echo-printing my code like this:
    $x = <>; print "x = $x";
    So I wanted to have a subroutine which did this:
    $x = <>; echo_print $x; # results in "x = (value of $x)";