Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Printing the code of a coderef

by Trizor (Pilgrim)
on Jun 26, 2007 at 05:35 UTC ( [id://623309]=note: print w/replies, xml ) Need Help??


in reply to Printing the code of a coderef

You're looking for B::Deparse. In fact, you have the usage almost correct, except instead of printcode the method is called coderef2text.

use B::Deparse; sub somecode { do { print "some stuff\n" } } my $somevar = B::Deparse->new(); print $somevar->coderef2text(\&somecode);

However you might want to read the docs, as B::Deparse is still in development and contains some caveats.

Replies are listed 'Best First'.
Re^2: Printing the code of a coderef
by Anonymous Monk on Jun 26, 2007 at 06:05 UTC
    Very helpful, but I get a weird nested structure as output, though it would be equivalent to the original code:
    { do { do { print "some stuff\n" } }; }
    Is there any way I can get it to print without the excessive do's?

      the new generation of data dumping does streamline this using B::Deparse

      % steph@apexPDell2 (/home/stephan/t1) % % date Tue Jun 26 15:04:14 2007 % steph@apexPDell2 (/home/stephan/t1) % % date; cat Some/Module.pm Tue Jun 26 15:04:27 2007 package Some::Module; sub somecode { do { print "some stuff\n" } } 1; % steph@apexPDell2 (/home/stephan/t1) % % perl -MDDS -MSome::Module -e 'Dump(\&Some::Module::somecode)'; date $CODE1 = sub { package Some::Module; do { do { print "some stuff\n" } }; }; Tue Jun 26 15:04:32 2007
      cheers --stephan
      I guess that's the best we can get now. I don't know what B::Deparse exactly does, but it seems to handle the do statement specially. As shown in another reply with Sub::Information, the result is the same with with Data::Dump::Streamer which in turn also uses B::Deparse. Consider and compare with the following code.
      use Data::Dump::Streamer; sub somecode { my $x = shift; if ($x) { print "x ok\n"; } else { print "what do you want?\n"; } return 1; } print Dump(\&somecode); __END__ # result: $CODE1 = sub { my $x = shift @_; if ($x) { print "x ok\n"; } else { print "what do you want?\n"; } return 1; };

      Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (None)
    As of 2024-04-25 00:51 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found