且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取传递给子程序的所有参数如在Perl字符串

更新时间:2023-11-03 18:50:40

Perl提供特殊调试钩,让你看到编译源文件的原始行。你可以写,每一个子程序调用时打印原有线路的自定义调试器。

Perl provides special debugging hooks that let you see the raw lines of compiled source files. You can write a custom debugger that prints the original line every time a subroutine is invoked.

下面,您可以指定要匹配一个或多个子程序;每一个匹配的子程序调用时,相应的行打印出来。

The following lets you specify one or more subroutines you want to match; every time a matching subroutine is invoked, the corresponding line is printed.

package Devel::ShowCalls;

our %targets;

sub import {
    my $self = shift;

    for (@_) {
        # Prepend 'main::' for names without a package specifier
        $_ = "main::$_" unless /::/;
        $targets{$_} = 1;        
    }
}

package DB;

sub DB {
    ($package, $file, $line) = caller;
}

sub sub {
    print ">> $file:$line: ",
          ${ $main::{"_<$file"} }[$line] if $Devel::ShowCalls::targets{$sub};
    &$sub;
}

1;


要跟踪的功能调用巴兹:: qux 在下面的程序:

sub foo {}
sub bar {}
sub Baz::qux {}

foo(now => time);
bar rand;
Baz::qux( qw/unicorn pony waffles/ );

运行:

$ perl -d:ShowCalls=foo,Baz::qux myscript.pl 
>> myscript.pl:5: foo(now => time);
>> myscript.pl:7: Baz::qux( qw/unicorn pony waffles/ );

请注意,这将只打印调用的第一行,所以像

Note that this will only print the first line of the invocation, so it won't work for calls like

foo( bar,
     baz );