
use v5.10;use strict;package Awesome;sub new { bless {steps => [],surprise => undef},shift;}sub say { print "awesome: ",$_[1],"\n";}sub prepare { my ($self,@steps) = @_; for my $s (@steps) { push @{$self->{steps}},sub { $self->say($s); if ($s eq 'pony') { $self->{surprise} = sub { $s; } } }; }}sub make { my $self = shift; while (my $step = shift @{$self->{steps}}) { $step->(); } if ($self->{surprise}) { printf("And you have surprise: %s\n",$self->{surprise}->()); }}sub DESTROY { warn "destroying";}package main;my $a = Awesome->new;$a->prepare('barbIE','pony','flash');$a->make(); 我的perl输出是
awesome: barbIEawesome: ponyawesome: flashAnd you have surprise: ponydestroying at /tmp/t.pl line 43 during global destruction.
而这个“在全局破坏期间”意味着物体不能以正常方式被破坏,因为它有一些循环引用.
但是,唯一的循环引用是由
push @{$self->{steps}},sub { $self->say($s); 我们在第一次关闭时使用$self.然后在make()里面我们将删除这些步骤和循环引用.但看起来这个嵌套的封闭与“惊喜”会产生问题.例如,如果我们不将“pony”传递给prepare(),那么输出将如预期的那样好:
awesome: barbIEawesome: flashdestroying at /tmp/t.pl line 43.
那么,perl中的嵌套闭包是否捕获了与已经捕获的上层闭包相同的变量,即使我们没有使用它们?
解决方法 Perl过去常常在嵌套的闭包中过度捕获,但自5.18以来它不会这样做.$tail -n 9 a.pl # ModifIEd to make clearer when the object is destroyed.package main;{ my $a = Awesome->new; $a->prepare('barbIE','flash'); $a->make();}print "done.\n";
.16.3t/bin/perl a.plawesome: barbIEawesome: ponyawesome: flashAnd you have surprise: ponydone.destroying at a.pl line 43 during global destruction.
.18.2t/bin/perl a.plawesome: barbIEawesome: ponyawesome: flashAnd you have surprise: ponydestroying at a.pl line 43.done.总结
以上是内存溢出为你收集整理的perl – 嵌套闭包和捕获的变量全部内容,希望文章能够帮你解决perl – 嵌套闭包和捕获的变量所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)