code_junkie

How can I get a call stack listing in Perl?

Nov 11th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. use Devel::StackTrace;
  2. my $trace = Devel::StackTrace->new;
  3. print $trace->as_string; # like carp
  4.  
  5. use Carp qw<longmess>;
  6. use Data::Dumper;
  7. sub A { &B; }
  8. sub B { &C; }
  9. sub C { &D; }
  10. sub D { &E; }
  11.  
  12. sub E {
  13. # Uncomment below if you want to see the place in E
  14. # local $Carp::CarpLevel = -1;
  15. my $mess = longmess();
  16. print Dumper( $mess );
  17. }
  18.  
  19. A();
  20. __END__
  21. $VAR1 = ' at - line 14
  22. main::D called at - line 12
  23. main::C called at - line 10
  24. main::B called at - line 8
  25. main::A() called at - line 23
  26. ';
  27.  
  28. my $stack_frame_re = qr{
  29. ^ # Beginning of line
  30. s* # Any number of spaces
  31. ( [w:]+ ) # Package + sub
  32. (?: [(] ( .*? ) [)] )? # Anything between two parens
  33. s+ # At least one space
  34. called [ ] at # "called" followed by a single space
  35. s+ ( S+ ) s+ # Spaces surrounding at least one non-space character
  36. line [ ] (d+) # line designation
  37. }x;
  38.  
  39. sub get_stack {
  40. my @lines = split /s*ns*/, longmess;
  41. shift @lines;
  42. my @frames
  43. = map {
  44. my ( $sub_name, $arg_str, $file, $line ) = /$stack_frame_re/;
  45. my $ref = { sub_name => $sub_name
  46. , args => [ map { s/^'//; s/'$//; $_ }
  47. split /s*,s*/, $arg_str
  48. ]
  49. , file => $file
  50. , line => $line
  51. };
  52. bless $ref, $_[0] if @_;
  53. $ref
  54. }
  55. @lines
  56. ;
  57. return wantarray ? @frames : @frames;
  58. }
Add Comment
Please, Sign In to add comment