Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

passing a variables name to a subroutine

by LANTI (Sexton)
on Feb 18, 2011 at 11:55 UTC ( #888887=perlquestion: print w/ replies, xml ) Need Help??
LANTI has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
for a debugging-sub I would like to pass the name of a variable to the sub. How is this possible?

What I have so far (untested yet):

say sdump($some_ref); sub sdump { my $ref = shift || croak('nothing to dump - missing ref'); my $depth = shift || 2; local $Data::Dumper::Maxdepth = $depth; return 'Dump of $var_name: ' . "\n" . Dumper($ref) }

How can I get the $var_name('$some_ref' in this exemple) into the sub?

Comment on passing a variables name to a subroutine
Download Code
Re: passing a variables name to a subroutine
by moritz (Cardinal) on Feb 18, 2011 at 12:13 UTC

      hmh ... seems not to work, if the dumped ref is a lexical variable in production-code. For the moment I live with this solution - not very elegant, because most of the time the identifying string will be same as the var-name:

      say sdump($pout, '$pout'); sub sdump { my $ref = shift || croak('nothing to dump - missing ref'); my $name = shift || 'n/a'; my $depth = shift || 2; local $Data::Dumper::Maxdepth = $depth; return "Dump of $name:\n" . Dumper($ref); }

      Any idea, how to call it this way?

      sdump('$pout');
        hmh ... seems not to work, if the dumped ref is a lexical variable in production-code.

        With which code did it not work? Did you try PadWalker as I suggested? How the the production code differ from the test code?

      Congrats on winning 888888. :-)

Re: passing a variables name to a subroutine
by Anonymous Monk on Feb 18, 2011 at 14:14 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://888887]
Approved by marto
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (10)
As of 2015-07-05 19:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls