Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Displaying a variable's name and value in a sub

by Smile-n-Nod (Initiate)
on Feb 14, 2011 at 22:58 UTC ( #888088=perlquestion: print w/replies, xml ) Need Help??

Smile-n-Nod has asked for the wisdom of the Perl Monks concerning the following question:

Consider this code:
sub show1 { ... } sub show2 { ... } my $a = 'foo'; show1($a); show2('$a');
How can I write either show1() or show2() so that STDOUT displays this:
$a = 'foo'
This is trivial in C/C++ using macros, but I can't figure out how to write either show1() or show2() so that it knows the name and value of the variable passed to it from a different scope.

Replies are listed 'Best First'.
Re: Displaying a variable's name and value in a sub
by roboticus (Chancellor) on Feb 14, 2011 at 23:13 UTC

    Smile-n-Nod:

    What should it print for these?

    show1(7.5); show1($foo{bar}{baz}); show1(cos(.866));

    Arguments aren't always variables with a name. Other than debugging and logging, I'd have a hard time coming up with a good use for knowing the variable's name. I usually just print the variable names that I use inside the subroutine in my log/debug statements.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Displaying a variable's name and value in a sub
by chromatic (Archbishop) on Feb 15, 2011 at 05:58 UTC

    You probably don't need to do this ever, but you can if you install PadWalker:

    use Modern::Perl; use PadWalker 'var_name'; sub show1 { my $name = var_name(1, \$_[0]); say "show1 called with $name"; }
Re: Displaying a variable's name and value in a sub
by wind (Priest) on Feb 14, 2011 at 23:46 UTC

    Instead of worrying about the variable name, I would suggest that you consider using caller so that you know where the show function was called from. The package name, file name, and line number are going to tell you a lot more debugging information than the name of a variable which is likely to be ambiguous anyway.

    - Miller

Re: Displaying a variable's name and value in a sub
by SuicideJunkie (Vicar) on Feb 14, 2011 at 23:35 UTC

    It is trivial to do it outside the sub hardcoded, so you just need to escape things in an eval correctly to do it with a variable variable name inside or outside the sub. PS: don't use $a or $b because they're magic sort variables.

    Validation of the parameters to the sub is left as an exercise for the reader! Also note that the variables you want to print have to be visible to the sub. If you're limiting the scope your variable properly, such a sub should be almost completely useless. ;)

    The inline loopy version is fairly generic and not as useless, but you should upgrade to Data::Dumper. It will let you print out arrays, hashes and complex nested and recursive data structures.

    use strict; use warnings; use Data::Dumper; my $scalar = 'foo'; my $other = 'bar'; print "\tStandalone\n"; print "\$scalar='$scalar'\n"; print "\tLoopy\n"; eval "print \"\$_='$_'\n\"" foreach ('$scalar', '$other'); print "\tNow using a sub just because you can\n"; debug('$scalar'); sub debug { eval "print \"\$_='$_'\n\"" while ($_ = shift) } my $variables = {scalar=>$scalar, other=>$other, relations=>{numbers=>{fib=>[0,1,1,2,3,5,8], pi=>22/7}, words=>{foo=>'bar', apple=>'fritter', password=>'$5hammer' +}}}; $variables->{other} = 'baz'; print Dumper $variables;
Re: Displaying a variable's name and value in a sub
by ciderpunx (Vicar) on Feb 14, 2011 at 23:16 UTC
    my $a = 'b'; sub show { my $c = shift; print $c . '=' . eval $c; } show('$a');
    But you almost certainly shouldn't be doing that, if you really care about the name of your variable pass it as a parameter ie. show('$b',$b);
    --
    Linux, perl, punk rock, cider: charlieharvey.org.uk.
Re: Displaying a variable's name and value in a sub
by ambrus (Abbot) on Feb 15, 2011 at 11:43 UTC
Re: Displaying a variable's name and value in a sub
by davido (Cardinal) on Feb 15, 2011 at 04:26 UTC

    I'm curious what task you're trying to accomplish. I was just interested in what task would require such an approach. Perhaps by understanding the bigger picture I or someone else here may be able to suggest a Perlish solution.


    Dave

Re: Displaying a variable's name and value in a sub
by trwww (Priest) on Feb 15, 2011 at 05:56 UTC

    You have to pass in the variable name:

    $ perl -MData::Dumper -Mwarnings -Mstrict -le 'my $quxx = 10; my $foo += {bar => 1, bazz => 2}; print Data::Dumper->Dump([$quxx, $foo], [qw( +quxx foo)]);' $quxx = 10; $foo = { 'bar' => 1, 'bazz' => 2 };
Re: Displaying a variable's name and value in a sub
by Marshall (Abbot) on Feb 15, 2011 at 09:42 UTC
    I find the idea, "This is trivial in C/C++ using macros" hard to believe. I can't see any trivial way without expanding the number of args to showx().

    Of course you can use the C pre-possessor to do macro expansion and send that result into Perl if you wanted to do so. The C pre-processor does not know any thing about the C language. I would be curious as what you come up with. But I doubt that your original claim is correct.

    sub show1 { ... } sub show2 { ... } my $a = 'foo'; show1($a); #desired print $a='foo' show2('$a'); #desired print $a='foo' $a = 'foobar'; show1($a); #desired print $a='foobar'
    Perl has position dependent variable passing, just like 'C'. "show1()" should be saying something like "name was $name" where "$name = shift;". For show1() to display a calling variable name, it would have to have an additional parameter, $souce_code_name.

    There is not a way to easily get the calling variable name from the sub that called this sub even with C macro expansion.

Re: Displaying a variable's name and value in a sub
by 7stud (Deacon) on Feb 15, 2011 at 00:37 UTC
    <deleted--didn't address the actual question>

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2019-07-22 10:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (14 votes). Check out past polls.

    Notices?