perl – 如何使用Devel :: Declare注入多行?
Devel::Declare
來注入多行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"; }
然後,$誰報告第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";]; }
但是引入不可接受的開銷,因為必須為每個引數呼叫__empty()函式.可以通過呼叫__empty()有條件地使用永遠不會評估為true的條件來消除開銷.
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";]; }
http://stackoverflow.com/questions/25171619/how-can-i-inject-multiple-lines-with-develdeclare