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

Consider the following code:

use Data::Dumper; my $sub = sub { my $filename = shift; return '/tmp/' . $filename; }; print Dumper($sub);

Executing it returns

$VAR1 = sub { "DUMMY" };

which is kinda what I expect, since as the Data::Dumper documentation points out, "Data::Dumper cheats with CODE references. If a code reference is encountered in the structure being processed (and if you haven't set the Deparse flag), an anonymous subroutine that contains the string '"DUMMY"' will be inserted in its place, and a warning will be printed if Purity is set."

So is there any other way, to see a string representation of a code ref? The reason I ask is that I'm generating arrays of code refs on the fly, and it would help my debugging if I could see what was generated.

Replies are listed 'Best First'.
Re: Is it possible to view a string representaion of a code ref?
by shmem (Chancellor) on May 13, 2009 at 23:57 UTC

    Several:

    use Data::Dumper; $Data::Dumper::Deparse = 1; my $sub; { my $x = "foo"; $sub = sub { my $filename = shift; return "/tmp/$x/" . $filename; }; } print Dumper($sub); __END__ $VAR1 = sub { my $filename = shift @_; return "/tmp/$x/" . $filename; };
    use Data::Dump::Streamer; my $sub; { my $x = "foo"; $sub = sub { my $filename = shift; return "/tmp/$x/" . $filename; }; } print Dump($sub); __END__ my ($x); $x = 'foo'; $CODE1 = sub { my $filename = shift @_; return "/tmp/$x/" . $filename; };
    use B::Deparse; my $deparse = B::Deparse->new; my $sub; { my $x = "foo"; $sub = sub { my $filename = shift; return "/tmp/$x/" . $filename; }; } print $deparse->coderef2text($sub),"\n"; __END__ { my $filename = shift @_; return "/tmp/$x/" . $filename; }

    update: added a block scope, from which you can see that out of those only Data::Dump::Streamer provides the sub's context.

      Only the B::Deparse solution seems to work in my case
      Active perl 5.6.1 build 635, MSWin32-x86-multi-thread
      Data::Dumper solution is still printing "DUMMY", i don't have Data::Dump::Streamer installed so I have not tested it

      Vivek
      -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
      Ah, very cool. Thanks ;-)