Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Coderef to String conversion?

by joe++ (Friar)
on Mar 08, 2003 at 09:16 UTC ( #241359=perlquestion: print w/replies, xml ) Need Help??
joe++ has asked for the wisdom of the Perl Monks concerning the following question:


If I try to dump a Perl structure from Data::Dumper, I get dummy functions in place of any CODE refs that happen to be in my data structure.

What I'm looking for is something similar to JavaScript's toString() method.

From the documentation of I got the impression that this is not possible in Perl:

"Data::Dumper" cheats with CODE references. If a code reference is encountered in the structure being processed, an anonymous subroutine that contains the string '"DUMMY"' will be inserted in its place, and a warning will be printed if "Purity" is set. (...) Someday, perl will have a switch to cache-on-demand the string representation of a compiled piece of code, I hope.
A quick demonstration:
#!/usr/bin/perl -w use strict; use Data::Dumper; my $test = { test => 1, code => sub { print 'Yeah'; }, aref => [ qw(1 2 3 4 5) ], }; print Dumper($test);
$VAR1 = { 'code' => sub { "DUMMY" }, 'aref' => [ '1', '2', '3', '4', '5' ], 'test' => 1 };
Is there really no work around or alternative possible?

Cheers, Joe

Replies are listed 'Best First'.
Re: Coderef to String conversion?
by jryan (Vicar) on Mar 08, 2003 at 09:33 UTC

    You'll need to use B::Deparse for this; for instance:

    use B::Deparse; use Data::Dumper; my $deparse = B::Deparse->new; print $deparse->coderef2text( sub{print 'Yeah'} )

    As for Data::Dumper, the newest version (the one that came with 5.8.0; if you don't have it, get it from the CPAN) has an option called Deparse; turn it on, and it will use B::Deparse to stringify coderefs for you:

    my $test = { test => 1, code => sub { print 'Yeah'; }, aref => [ qw(1 2 3 4 5) ], }; $Data::Dumper::Deparse = 1; print Dumper($test);

      Cool, B::Deparse just does the trick!
      I'm using 5.6.1 right now, and I don't want to limit my script to 5.8x for the time being...


      Cheers, Joe

        Keep in mind that B::Deparse isn't guaranteed to produce correct results and that it won't help you with any bound lexicals if you're using closures. But since you aren't writing Obfuscations your code will probably come out just fine.

        Seeking Green geeks in Minnesota

        You don't need perl 5.8.0, just the version of Data::Dumper that comes with it. You can find it here.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://241359]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2019-02-19 10:28 GMT
Find Nodes?
    Voting Booth?
    I use postfix dereferencing ...

    Results (104 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!