Perl Stack Trace(Devel :: Trace)

时间:2013-12-12 08:58:41

标签: perl stack-trace trace

我尝试Devel::Trace使用它作为代码的调试器来获取perl堆栈跟踪。

perl -d:Trace <pgm>

还尝试在perl代码中使用$Devel::Trace::TRACE = 0;Devel::Trace::trace('on');。但我无法得到痕迹。

有人可以通过示例说明perl代码中Devel::Trace的用法。

1 个答案:

答案 0 :(得分:3)

Devel::Trace不会产生堆栈跟踪。相反,它打印出当前正在执行的语句。例如:

$ cat script.pl
    use feature 'say';
    my $foo = "bar";
    say $foo;
$ perl -d:Trace script.pl
>> script.pl:2:     my $foo = "bar";
>> script.pl:3:     say $foo;
bar

在您的代码中,您可以为特定区域打开和关闭跟踪:

$ cat script.pl
    use feature 'say';
    my $foo = "bar";
    for my $n (1 .. 3) {
      local $Devel::Trace::TRACE = 0;
      say $foo x $n;
    }
    say "That were some ${foo}s";
$ perl -d:Trace script.pl
>> script.pl:2:     my $foo = "bar";
>> script.pl:3:     for my $n (1 .. 3) {
>> script.pl:4:       local $Devel::Trace::TRACE = 0;
bar
>> script.pl:4:       local $Devel::Trace::TRACE = 0;
barbar
>> script.pl:4:       local $Devel::Trace::TRACE = 0;
barbarbar
>> script.pl:7:     say "That were some ${foo}s";
That were some bars

如您所见,当我在该范围内进行跟踪时,say $foo x $n行未包含在跟踪输出中。

如果你想要一个堆栈跟踪(如“调用堆栈跟踪”),那么使用Carp模块:

$ cat script.pl
    use Carp ();

    foo("Hello World");

    sub foo { bar(@_) }
    sub bar { baz(@_) }
    sub baz { qux(@_) }
    sub qux { Carp::cluck "Howdy!" }
$ perl script.pl
Howdy! at so1.pl line 8.
        main::qux('Hello World') called at script.pl line 7
        main::baz('Hello World') called at script.pl line 6
        main::bar('Hello World') called at script.pl line 5
        main::foo('Hello World') called at script.pl line 3