Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Displaying a variable's name and value in a sub

by SuicideJunkie (Vicar)
on Feb 14, 2011 at 23:35 UTC ( [id://888096]=note: print w/replies, xml ) Need Help??


in reply to Displaying a variable's name and value in a sub

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://888096]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2024-04-23 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found