perl - 如何使用 Devel::Declare 注入(inject)多行?

标签 perl

我想使用 Devel::Declare 注入(inject)多行 Perl 代码。但是,Devel::Declare::set_linestr()无法处理多行。

通常我会将多个语句连接在一起作为一行。这些语句必须位于不同的行上,以保留它们的行号以用于错误报告。这是为了解决this bug in Method::Signaturesthis related bug .我对替代解决方案持开放态度。

例如, Method::Signatures 当前将这个代码...

use Method::Signatures;

func hello(
    $who = "World",
    $greeting = get_greeting($who)
) {
    die "$greeting, $who";
}

……进入这个……
func  \&hello; sub hello  { BEGIN { Method::Signatures->inject_scope('') }; my $who = (@_ > 0) ? ($_[0]) : ( get_greeting($who)); my $greeting = (@_ > 1) ? ($_[1]) : ( "Hello"); Method::Signatures->too_many_args_error(2) if @_ > 2;
    die "$greeting, $who";
}
die $who然后报告第 4 行而不是第 7 行。

我希望它改为这个(或者可能涉及 #line )。
func  \&hello; sub hello  { BEGIN { Method::Signatures->inject_scope('') };
    my $who = (@_ > 0) ? ($_[0]) : ( "World");
    my $greeting = (@_ > 1) ? ($_[1]) : ( get_greeting($who));
    Method::Signatures->too_many_args_error(2) if @_ > 2;
    die "$greeting, $who";
}

这不仅忠实地再现了行号,get_greeting croak 它将报告已从正确的线路调用。

最佳答案

根据您自己的答案,以下工作:

sub __empty() { '' }

sub parse_proto {
    my $self = shift;
    return q[print __LINE__."\n"; Foo::__empty(
);print __LINE__."\n"; Foo::__empty(
);print __LINE__."\n";];
}

但是引入了 Not Acceptable 开销,因为 __empty()必须为每个参数调用函数。调用 __empty() 可以消除开销。有条件地使用永远不会为真的条件。
sub __empty() { '' }

sub parse_proto {
    my $self = shift;
    return q[print __LINE__."\n"; 0 and Foo::__empty(
);print __LINE__."\n"; 0 and Foo::__empty(
);print __LINE__."\n";];
}

关于perl - 如何使用 Devel::Declare 注入(inject)多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171619/

相关文章:

linux - 为什么 fork() 不立即给出正确的 pid?

perl - 我如何使用 Perl 组织这些数据?

Perl 通过 DOM 查找 Web 链接

regex - 为什么 perl regex '*?' 保持贪婪?

linux - perl 中的 '\b' 字符是如何工作的?

Perl:用一些独特的约束分解字符串

python - 将行转换为列

perl - 打开文件并通过调整覆盖该文件且不进行备份

perl - autodie-pragma 对编码有影响吗?

arrays - Perl-我在寻找什么功能?将多个规则分配给指定结果