【问题标题】:In perl, is there a way to make subroutines print their name and arguments when called?在 perl 中,有没有办法让子程序在调用时打印它们的名称和参数?
【发布时间】:2011-08-10 07:47:24
【问题描述】:

我需要快速了解在一堆意大利面条代码 perl 模块中调用了哪些子例程。

我可以编写一个脚本来遍历所有模块并添加代码以在每个子例程的开头打印出子例程名称和参数。

但是有没有办法覆盖内部 perl 的“子例程”机制本身来做到这一点?

代码在 mod_perl 下运行,所以我不能轻易使用调试器。

【问题讨论】:

  • 感谢 Devel::Trace 和 Apache 文档的指点,但使用 Moose 作为@cnicutar 描述如下是迄今为止最简单的方法。

标签: perl internals


【解决方案1】:

running under Apache via mod_perl时,你可以通过NYTProf运行代码

【讨论】:

    【解决方案2】:

    我知道你说你“不能轻易使用调试器”,因为你在 mod_perl 下运行,但是有一些选项可以做到这里描述的:

    http://perl.apache.org/docs/1.0/guide/debug.html#Non_Interactive_Perl_Debugging_under_mod_perl

    【讨论】:

      【解决方案3】:

      您可以使用 Moose::MethodModifiers。我对Moose 了解不多,但是从手册中我可以看到您可以做到。来了。

      #!/usr/bin/perl -w
      use 5.010;
      use strict;
      use Moose;
      
      sub sub_one {
          say "I am sub one!";
      }
      
      sub sub_two {
          say "Guess who!";
      }
      
      # Note that the name of the function being modified isn't passed in in
      # any way
      
      for my $func qw(sub_one sub_two) {
          around $func => sub {
              my $orig = shift;
      
              say "Running ${func}(@_)";
      
              # call the original sub
              my $self = shift;
              $self->$orig(@_);
          }
      }
      
      sub_one(21, 12);
      sub_two();
      

      这会产生类似的东西

      cnicutar@aiur:~$ perl method_modifiers.pl
      Running sub_one(21 12)
      I am sub one!
      Running sub_two()
      Guess who!
      

      请注意,我只是一个初学者,所以请谨慎使用该代码。

      【讨论】:

        【解决方案4】:

        Devel:Trace 将显示子程序调用和参数。它还将显示执行的每一行代码,这可能比您需要的更详细。

        perl -d:Trace program
        

        Devel::DumpTrace 将更加详细,同时显示变量的

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-29
          • 1970-01-01
          • 1970-01-01
          • 2014-04-21
          • 2023-01-17
          • 2018-12-26
          相关资源
          最近更新 更多