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

**************

UPDATE: Figured this out myself. I needed to add $Data::Dumper::Deparse = 1;

**************

I'm debugging a program that passes around coderefs as part of an html reformat. FWIW, the coderef winds up being an argument to Html::Element::look_down.

It would be convenient to examine the contents of the coderef. I was hoping to be able to do this with Data::Dumper, but I haven't figured out a way to do this. Data::Dumper did have some examples that seemed to touch on code refs, but they don't seem to do what I want.

Is there a way, Data Dumper or otherwise?

Looking for something along the lines of

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Test::More qw(no_plan); $Data::Dumper::Deparse = 1; # I needed to add this my $subroutine = sub { print "test" }; print Dumper($subroutine); #nah, this just gives "$VAR1 = sub { "DUMMY +" };" my $wanted = 'print "test"'; my $got = get_code($subroutine); is($got, $wanted); sub get_code { defined(my $coderef = shift) or die "no code ref"; return "whatever"; }
Thanks for leading me to better perl!

Replies are listed 'Best First'.
Re: How to get code from a coderef?
by diotalevi (Canon) on Jan 20, 2006 at 16:48 UTC

    You could have done that with B::Deparse directly. Data::Dumper just uses it. Neither of those modules dump closures correctly. For that, use Data::Dump::Streamer. DDS also uses B::Deparse to dump the code but has additional magic to reconstruct the lexical environment. Right now, this is the only way to dump closures.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re: How to get code from a coderef?
by pileofrogs (Priest) on Jan 20, 2006 at 17:08 UTC

    I'm a big (but newly converted) YAML fan.

    Does anyone with more experience than me have an opinion on YAML's behavior with code refs?

    --Thanks

    Pileofrogs

    Update: (added Sat Midnight, US Pacific time)

    Just to satisfy my curiosity:

    #! /usr/bin/perl -w -T use YAML; my $foo = sub { print "bar" }; print Dump($foo)."\n";

    Produces:

    --- !perl/code: '{ "DUMMY" }'

      What is YAML's behavior? I'd imagine that YAML shouldn't even attempt to touch them because code references aren't portable to the other platforms YAML is supposed to work in. YAML is a data format, not a perl dumper.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        YAML actually uses B::Deparse to dump. Remember the way back of YAML is much slower and unsafe than having a coderef on a perl script. Diego de Lima