Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

printing variable and evaluation

by f77coder (Beadle)
on Jul 07, 2017 at 09:55 UTC ( #1194458=perlquestion: print w/replies, xml ) Need Help??

f77coder has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I think this is easy but can't seem to find the correct way to do this. I did search but can't seem to find the right solution.

I have a variable, it is a single object, number (int,float) or string(word,char) without using something like DataDumper to print the variable and the value of the variable

>>Pprint($variable) >> $variable, evaluation of $variable
Thanks!

Replies are listed 'Best First'.
Re: printing variable and evaluation (updated)
by haukex (Bishop) on Jul 07, 2017 at 10:36 UTC

    That's nontrivial, but if you're really interested in how to do this, then look at the code of Data::Dumper::Names, it uses PadWalker to inspect the lexical variables in the calling scope.

    use Data::Dumper::Names; my $foo = "Bar"; print Dumper($foo); __END__ $foo = 'Bar';

    Update: I guess I should expand on the "nontrivial" a little more. There is no "simple" mechanism in Perl for a subroutine like your proposed pprint to know where its arguments in @_ came from. Consider the simple case of my @bar = ("a","b"); foo(@bar,"c"), what the sub foo sees is @_ = ("a","b","c"), with no easy way of knowing where those values came from, and in the case of the literal "c" there is no variable. Diving into this topic will bring you to places like caller, Symbol Tables, lexical variables and modules like PadWalker, and perhaps even the guts of the debugger, "which range from difficult to impossible to understand for anyone who isn't incredibly intimate with Perl's guts. Caveat lector."

      Thank you for the insights.

      This "Guts of Perl debugging" looks a bit intimidating.

      Is there no way to read the input variable

      $variable

      as a literal string before any processing or evaluation is done? then let perl do an eval of the variable?

        Given what I already said (it is unwise) and good modules suggested as symbol table inspector ie Data::Dumper::Names which uses PadWalker you probably mean something like the following (working for scalar, must be modified for arrays and hashes)?

        perl -e " my $x = 15; print map {$_.' = '.eval eval{$_} } '$x' " $x = 15

        Again: this leads you on a wrong path, might be worth to know but not to be used

        L*

        There are no rules, there are no thumbs..
        Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: printing variable and evaluation
by TheDamian (Priest) on Jul 07, 2017 at 21:33 UTC

    Did you try Data::Dx (recently added to CPAN)?

    It's a "named dumping" wrapper around Data::Dump, but it uses keywords, rather than source filters, so it's inherently much safer.

Re: printing variable and evaluation
by kikuchiyo (Friar) on Jul 07, 2017 at 11:34 UTC

    I suppose you could write a source filter that scans the code at BEGIN time and replaces every instance of Pprint($variable) with something like print("\$variable returns $variable");, but it sounds like a recipe for disaster. It would be very fragile, bound to break at every imaginable edge case.

    I'd take a step back and think about what you actually want to achieve. In the end, you want to see in your output not just the value of a variable, but some context (semantic information) for that value as well. The name of the variable is a poor source of that context. It's better to provide it explicitly.

    So do something like print("setting foo/bar/baz = '$variable'"). The point is to accompany the variable printout with an explanation that makes sense for you in the context of your application (and will make sense in 5 years in the future). You can write a helper function for it if you want.

      In the end, you want to see in your output not just the value of a variable, but some context (semantic information) for that value as well.

      That's a good point! Data::Dump provides a ddx function that includes the file name and line number from where it was called in the printout.

Re: printing variable and evaluation
by Eily (Monsignor) on Jul 07, 2017 at 10:03 UTC

    without using something like DataDumper to print the variable and the value of the variable
    Why not? It's a core module, you don't even have to install it.

    What do you mean by "printing the variable and the value of the variable" anyway? Do you mean the variable name and its value? Like print "\$variable's value is $variable\n"; ?

      Thanks for the help.

      I've become too reliant on modules and want to sharpen my own coding skills.

      say variable is $reallyLongPathName
      pprint($reallyLongPathName)
      would return
      $reallyLongPathName returns /remoteserver/disk5/usr/local/lib/libavcod +ec.a
        Hello,

        in my little experience, when you try to access the variable name you are in the wrong path. Use Data::Dumper or better the non CORE module Data::Dump dd method to show up your variables.

        L*

        There are no rules, there are no thumbs..
        Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

        I've become too reliant on modules and want to sharpen my own coding skills.

        I would say that, generally, that's a logical fallacy. Modules are simply tools. Programmers are tool-makers. When you go into a machine shop you see the machinist making tools *that don't already exist* to accomplish a specific task, not crafting a hammer on his anvil (using another hammer? where did that one come from?), or turning a drill bit on his lathe.

        Learning how to select and use the existing tools (especially the ones already built into the language) is a fundamental skill for a programmer, and becoming adept at implementing such properly is every bit "sharpening your coding skills."

        In my humble opinion, your time and energy would be better invested in practicing writing clean, efficient application code, using the basic toolkit you've already selected by choosing to code in Perl.


        The way forward always starts with a minimal test.
Re: printing variable and evaluation
by LanX (Cardinal) on Jul 08, 2017 at 00:05 UTC
    The best approach I know is Data::Dumper::Lazy , since it doesn't suffer from the limitations of the other modules suggested so far.

    Unfortunately the author is too perfectionist and Data::Dumper::Lazy to finish it properly ;)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2020-10-23 06:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (235 votes). Check out past polls.

    Notices?