经典的闭包问题
引用计数器不能减为零 造成垃圾回收不能释放 最简单的办法 用local替代my Date: Mon, 24 Aug 2009 13:30:25 +0800 Subject: [PerlChina] Re: 变量作用域的问题 From: [email protected] To: [email protected] 我最后按照全局变量的方式来处理了。 十分感谢James和孙叔昌的帮助和建议,受益颇多。 Best regards Zhang JiaQiang 2009/8/23 Qiang (James) <[email protected]> 忘记回答你的问题了, hehe. 除了用上次连接里提供的匿名函数等解决办法外(在 使用嵌套函数情况下),我觉得也只能使用全局变量了,这样的解决方法简单易维 护( 和让你过几天后再看这段程序时要用5分钟才懂的程序比要好很多 :) )。 Qiang > >> use strict; >> # main begin >> ..... >> >> find( \&Wanted,$dir); >> >> sub Wanted >> { >> if ( $_ =~ /some reg/ ){ >> Parser_XML($_); >> } >> } >> >> sub Parser_XML { >> my $xmlfile = shift; >> my $tag_count; >> $parser->setHandlers( Start => \&startElement ); >> $parser->parsefile($xmlfile); >> print "There is $count in this xml file\n"; >> >> sub startElement { >> ...... >> $tag_count++ if $element == 'TAG'; >> } >> >> } >> >> >> >> Best regards >> Zhang JiaQiang >> >> >> >> 2009/8/23 Qiang (James) <[email protected] >> <mailto:[email protected]>> >> >> zhang jiaqiang wrote: >> > 大家好, >> > >> > 新手想不太明白一个变量作用的问题,请帮忙看看。 >> > >> > 我的问题是如何理解$x后两次没有值,为什么在函数in_a里还有值?而且 >> 第三次循 >> > 环的时候这个值怎么成2了? >> >> 简单的解释是嵌套函数的原因。复杂的这里讲的很清楚,就不和你重复了。。 >> >> >> http://perl.apache.org/docs/general/perl_reference/perl_reference.html#my____Scoped_Variable_in_Nested_Subroutines >> >> >> 另外,没有特别需要,没有人会这么写 Perl 程序。 >> >> Qiang >> >> >> > >> > 简化的程序如下: >> > >> > for $i (0..2){ >> > a(); >> > } >> > sub a >> > { >> > my $x ; >> > in_a(); >> > print $i,":\t",$x,"\n"; >> > undef $x; >> > sub in_a >> > { >> > $x++; >> > print "in_a:$x\n"; >> > } >> > } >> > >> > 执行结果: >> > in_a:1 >> > 0: 1 >> > in_a:1 >> > 1: >> > in_a:2 >> > 2: >> > >> > >> > >> > Best regards >> > Zhang JiaQiang >> > >> > >> > > >> >> >> >> >> >> >> > _________________________________________________________________ 無料で使える25GB。USBメモリの代わりに、Webに保存 http://clk.atdmt.com/GBL/go/153787332/direct/01/ --~--~---------~--~----~------------~-------~--~----~ 您收到此信息是由于您订阅了 Google 论坛“PerlChina Mongers 讨论组”论坛。 要在此论坛发帖,请发电子邮件到 [email protected] 要退订此论坛,请发邮件至 [email protected] 更多选项,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问该论坛 -~----------~----~----~----~------~----~------~--~---
