in reply to Turning a reference to a subroutine back into code

Another alternative is B::Deparse
use B::Deparse; sub dumpsub { print "sub ",B::Deparse->new->coderef2text(shift),"\n" } dumpsub \&dumpsub;

Output:

sub { BEGIN {${^WARNING_BITS} = "\377\377\377\377\377\377\377\377\377\37 +7\377\177"} use strict 'refs'; print 'sub ', 'B::Deparse'->new->coderef2text(shift @_), "\n"; }


Unless I state otherwise, my code all runs with strict and warnings

Replies are listed 'Best First'.
Re^2: Turning a reference to a subroutine back into code
by citromatik (Curate) on Apr 18, 2008 at 08:44 UTC

    Nice example

    Be aware that if you plan to do this with a closure, B::Deparse doesn't pack any variable that the subroutine has closed over. Here is the same example that I posted above using B::Deparse:

    use strict; use warnings; use B::Deparse; sub makeGreeting { my $str = "Hello "; return sub { my ($name) = @_; print "$str $name\n"; } } my $greet = makeGreeting(); my $deparse = B::Deparse->new(); print $deparse->coderef2text($greet);

    Outputs:

    { use warnings; use strict 'refs'; my($name) = @_; print "$str $name\n"; }

    Variable $str appears in the output but its declaration is not "packed" inside the code

    citromatik