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;

In reply to Re: Displaying a variable's name and value in a sub by SuicideJunkie
in thread Displaying a variable's name and value in a sub by Smile-n-Nod

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.