How can I get a call stack listing in Perl?

后端 未结 8 698
慢半拍i
慢半拍i 2020-12-02 08:59

Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls preceding a current position in a Perl script?

I need to make chan

相关标签:
8条回答
  • 2020-12-02 09:28

    You can use Devel::StackTrace.

    use Devel::StackTrace;
    my $trace = Devel::StackTrace->new;
    print $trace->as_string; # like carp
    

    It behaves like Carp's trace, but you can get more control over the frames.

    The one problem is that references are stringified and if a referenced value changes, you won't see it. However, you could whip up some stuff with PadWalker to print out the full data (it would be huge, though).

    0 讨论(0)
  • 2020-12-02 09:28

    This code works without any additional modules. Just include it where needed.

    my $i = 1;
    print STDERR "Stack Trace:\n";
    while ( (my @call_details = (caller($i++))) ){
        print STDERR $call_details[1].":".$call_details[2]." in function ".$call_details[3]."\n";
    }
    
    0 讨论(0)
  • 2020-12-02 09:29

    caller can do that, though you may want even more information than that.

    0 讨论(0)
  • 2020-12-02 09:37

    There's also Carp::confess and Carp::cluck.

    0 讨论(0)
  • 2020-12-02 09:37

    Moving my comment to an answer:

    1. Install Devel::Confess the right way

      cpanm Devel::Confess
      
    2. Run with

      perl -d:Confess myscript.pl
      

    On errors, this will show the whole call stack list.

    0 讨论(0)
  • 2020-12-02 09:41

    One that is more pretty: Devel::PrettyTrace

    use Devel::PrettyTrace;
    bt;
    
    0 讨论(0)
提交回复
热议问题