Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Any way to access the contents of a block eval?

by chromatic (Archbishop)
on Oct 11, 2007 at 00:10 UTC ( #644115=note: print w/ replies, xml ) Need Help??


in reply to Any way to access the contents of a block eval?

Easy!

#!/usr/bin/perl use strict; use warnings; use B::Deparse; sub get_eval_text { my $start = shift; # turn the invoking subroutine into a B::Op-derived object my ($package, $sub, $end) = (caller(1))[0, 3, 2]; my $subref = do { no strict 'refs'; *{ $package . '::' . $sub }{C +ODE} }; my $cv = B::svref_2object( $subref ); # create a B::Deparse object and give it a sub to deparse (in part +) my $deparse = B::Deparse->new(); $deparse->{curcv} = $cv; # search the optree for the first op on the eval {} line my $op = deparse_from($cv->START, $start); # and deparse from that op return $deparse->deparse($op, 0) if $op; } sub deparse_from { my ($start, $line) = @_; for (my $op = $start; $$op; $op = $op->next()) { # look for nextstate ops next unless $op->isa( 'B::COP' ); # ... specifically the one representing the start of the eval +{} next unless $op->line == $line; # then grab the sibling op in the tree: leavetry return $op->sibling; } return; } sub main { my $x = 10; my $y = 20; eval { my $x = 1; my $y = $x; die 'aaaarrrr' }; print( $@, get_eval_text( __LINE__ - 1 ) ) if $@; } main();

I haven't found a way to get rid of __LINE__ - 1 reliably, but if you're willing to add that, here you go.


Comment on Re: Any way to access the contents of a block eval?
Select or Download Code
Replies are listed 'Best First'.
Re^2: Any way to access the contents of a block eval?
by adrianh (Chancellor) on Oct 12, 2007 at 13:02 UTC
    Easy!

    Impressive! You are a sick, sick man :-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (14)
As of 2015-07-31 21:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (282 votes), past polls