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

I need some advice and help here. I am trying to print name of the input argument inside a sub routine.snippet of my code:
my $var = 10; sub print_name{ *glob = \$_[0]; print "Name of the variable ".*{glob}{NAME}."\n"; } print_name $var; Output: glob Expected output: var
Is it possible to get name of scalar in Perl or is it only for Typeglob.

Replies are listed 'Best First'.
Re: To print name of a scalar
by syphilis (Archbishop) on Dec 18, 2010 at 06:50 UTC
    This will work:
    use warnings; use PadWalker qw(var_name);; my $var = 10; print_name(\$var); sub print_name { print var_name(1, shift); }
    However, according to the PadWalker docs, it works only if $var is a "my" variable.

    Cheers,
    Rob
Re: To print name of a scalar
by davido (Cardinal) on Dec 18, 2010 at 12:18 UTC

    Lexicals ('my' variables) aren't in the global symbol table. They don't appear in the %:: special variable's structure either (for the same reason). If it were a global via our, use vars, or non-adherence to use strict, then it does show up in the global symbol table, and can be referenced through %::. But even that is a little awkward. You don't really know by snooping in %:: when or where the variable first shows up in the script.

    I'm not sure what you're after, but could you use a tied scalar so that you're able to create a class of scalar that knows its name by object method?


    Dave

      I was just experimenting reading perlsub. got stuck so wanted to know more. Thank you.
Re: To print name of a scalar
by JavaFan (Canon) on Dec 18, 2010 at 14:02 UTC
    I am trying to print name of the input argument inside a sub routine
    What if the input argument doesn't have a name? What do you expect the answer to be in the following cases:
    @foo = (10); sub bar {10}; $baz = 5; $qux = 2; @quux = (); $fred = 100 +; print_name 10; print_name \10; print_name ${\10}; print_name [10]; print_name @foo; print_name $foo[0]; print_name bar; print_name $baz * $qux; print_name; print_name undef; print_name @quux; print_name sqrt $fred; print_name do {my $waldo = 10}; print_name sub {10}->();
      I am a newbie in Perl. My assumption while doing this experiment was that, subroutine will be passed a scalar variable declared as my. example:
      my $var; print_name $var;
      Your question made me realize all possible scenario which I had totally forgotten about. Thank you. Will work towards it.