perl – 是否为新的子程序调用或新的@_重用了@_的元素?

前端之家收集整理的这篇文章主要介绍了perl – 是否为新的子程序调用或新的@_重用了@_的元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想这取决于背景.

>当进行& func调用时,它会被重用
>它是为所有其他呼叫创建的

我有this code,我在第1004行得到了意外的评估:

sub save_context {
    @DB::context =  ( \@_,(caller 2)[8..10],$@,$_ );  # line 1004
    print_state "\nTRAPPED IN  ","\n\n"   if _ddd;
    DB::state( 'inDB',1 );
}

这个堆栈跟踪:

DB /x/local/lib/perl5/Devel/DebugHooks.pm 1419 DB::orig_frames 
DB /x/local/lib/perl5/Devel/DebugHooks.pm 1460 DB::push_frame 
DB /x/local/lib/perl5/Devel/DebugHooks.pm 1004 DB::__ANON__[/x/local/lib/perl5/Devel/DebugHooks.pm:1460] 
DB /x/local/lib/perl5/Devel/DebugHooks.pm 1004 (eval) 
DB /x/local/lib/perl5/Devel/DebugHooks.pm 1251 DB::save_context 
DB /x/local/lib/perl5/Devel/DebugHooks.pm 1288 DB::DB_my 1
MyApp::Controller::User /x/lib/MyApp/Controller/User.pm 41 DB::DB 1
MojolicIoUs /x/local/lib/perl5/MojolicIoUs.pm 133 MyApp::Controller::User::list 
MojolicIoUs::Plugins /x/local/lib/perl5/MojolicIoUs/Plugins.pm 15 MojolicIoUs::__ANON__[/x/local/lib/perl5/MojolicIoUs.pm:133] 
...

从我的日志文件中我可以看到调用DBIx :: Class :: DESTROY子:

DB::sub  DB::state: l:1 d:0 s:5 t:0  /x/local/lib/perl5/Devel/DebugHooks.pm:1004  -->  DBIx::Class::DESTROY

为什么推迟对象破坏?我想这在某种程度上与@_有关

任何建议都赞赏这可能会触发对象破坏

解决方法

在没有参数列表的& func调用中,不仅@_的元素被重用,整个@_被重用.
sub main {
    print "main: @_ is ",\@_,"\n";
    func(@_);  # Values from @_ are copied into new @_. @_ after call: 1 2 3
    &func;     # Origin @_ is passed down.           So @_ after call: 2 3
}

sub func {
    print "func: @_ is ","\n";
    shift @_;  # Here @_ is modified. Pay attention what values @_ left after call
}

main(1,2,3);  # @_ will be initialized by: 1 2 3

典型输出

main: @_ is ARRAY(0xfc5958)
@_ initial: 1 2 3
func: @_ is ARRAY(0xfc5a00)
@_ after func(): 1 2 3
func: @_ is ARRAY(0xfc5958)
@_ after &func: 2 3

从main进入& func调用,@ _未以任何方式进行本地化,复制或更改.从& func调用改变@_ inside func会影响调用者中的@_,但是从func()调用改变它不会.

猜你在找的Perl相关文章