我想使用 Devel::Declare
注入(inject)多行 Perl 代码。但是,Devel::Declare::set_linestr()
无法处理多行。
通常我会将多个语句连接在一起作为一行。这些语句必须位于不同的行上,以保留它们的行号以用于错误报告。这是为了解决this bug in Method::Signatures和 this 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/