in reply to How to retrieve the name of a variable ?

mascip:

In addition to toolic's suggestions, you could try Smart::Comments. If you're feeling adventurous, you could even use symbolic references. In general, not a great habit to get into, but for some tasks like this, they're not so bad.

$ cat t.pl #!/usr/bin/perl # Prevent symbolic references, etc. in general use strict; use warnings; # Use our instead of my to ensure that the value is accessible our $boom = 'Kaboom!'; our $bam = 'Kerblam!'; + # Unfortunately, the call looks odd... say_var('boom'); say_var('bam'); sub say_var { # Turn off strict for now no strict; my $t = shift; print "\$$t = >$$t<\n"; } $ perl t.pl $boom = >Kaboom!< $bam = >Kerblam!<

.... somehow I feel that I'll be roasted for suggesting such a thing ....

...roboticus

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

Replies are listed 'Best First'.
Re^2: How to retrieve the name of a variable ?
by mascip (Pilgrim) on Jul 19, 2012 at 00:15 UTC

    This IS a cool simple solution, thanks. I'll go for the CPAN one for now, though =)
    I don't remember why, i had decided to not use Smart::Comment at the time. I might re-change my mind.

      mascip:

      I'll go for the CPAN one for now, though =)

      Good call! I only suggested it because it was the only thing I ever thought that symbolic references might be good for. But when I saw that toolic had a better answer, I just didn't feel like throwing it away. (It's the first time I've used 'em, and the fact that you need to declare the variables with 'our' instead of 'my' made me bang my head a bit trying to figure out why I couldn't get it working...)

      ...roboticus

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

      The main reason not to use Smart::Comments is that it's a source filter: it changes the code of your program between when perl loads and when your program compiles. (Or while your program compiles.) This can introduce bugs or unintended effects which would be very hard to debug.

      Of course, it's a well-written module and has been used by many without that happening, but the possibility still exists. Your choice if you want to take the risk.

        Thank you !
        I decided to not use any source filters unless if really needed, as i wouldn't know how to debug it. I guess that you'd need to use B::Deparse? (which re-builds perl code, form the compiled code, so you can see what has been effectively executed). I prefer just not taking the risk right now.

        Smart::Comments also redirects all the information it provides to STDERR, which is not displayed on the standard output, under Test::NoWarnings.
        See there why i use Test::NoWarnings : 0==undef, that's annoying. Is it?.

        One could follow the "use Smart::Comments;" with something like "Filter::tee __PACKAGE__.'.tee';" and examine the results in the event that something funky happens.