5

我正在尝试学习Devel::Declare以尝试重新实现PDL::NiceSlice没有源过滤器的东西。当我注意到它正在从我的脚本中删除下一行时,我正在到达某个地方。为了说明这一点,我做了一个最小的例子,其中可以使用comment关键字从代码中删除整行,即使该行上有很多裸词也允许编译。

#Comment.pm
package Comment;

use strict;
use warnings;

use Devel::Declare ();

sub import {
  my $class = shift;
  my $caller = caller;

  Devel::Declare->setup_for(
      $caller,
      { comment => { const => \&parser } }
  );
  no strict 'refs';
  *{$caller.'::comment'} = sub {};

}

sub parser {
  #my $linestr = Devel::Declare::get_linestr;
  #print $linestr;

  Devel::Declare::set_linestr("");
}

1

#!/usr/bin/env perl
#test.pl

use strict;
use warnings;

use Comment;

comment stuff;

print "Print 1\n";
print "Print 2\n";

仅产出

Print 2

我错过了什么?

PS如果我应该解决这个问题,我可能会有更多问题D::D,所以提前谢谢!

4

1 回答 1

4

好的,我明白了。使用perl -MO=Deparse test.pl你得到:

use Comment;
use warnings;
use strict 'refs';
comment("Print 1\n");
print "Print 2\n";
test.pl syntax OK

这告诉我 if 强制comment调用该函数。经过一些实验,我发现我可以将输出设置为comment()显式调用,这样它就不会尝试调用comment接下来的任何内容。

sub parser {
  Devel::Declare::set_linestr("comment();");
}

所以deparse是:

use Comment;
use warnings;
use strict 'refs';
comment();
print "Print 1\n";
print "Print 2\n";
test.pl syntax OK

以及正确的输出。

于 2011-08-09T00:04:02.687 回答