- 论坛徽章:
- 0
|
求教各位高手,在《Intermediate Perl》第七章中关于子程序引用有一段代码,大致如下:
use File::Find;
sub create_find_callback_that_sums_the_size{
my $total_size = 0;
return sub{
if(@_){return $total_size;}
else{$total_size += -s if -f;}
};
}
my $callback = create_find_callback_that_sums_the_size();
find($callback, '.');
my $total_size = $callback->('dummy');
print $total_size,"\n";
根据我的理解,create_find_callback_that_sums_the_size子程序的返回值是一个匿名子程序,当该子程序没有参数时,则计算$total_size的值;而当子程序有参数时,则返回$total_size的值。
但是不明白书里面的解释,为什么"If we stick the definition of $total_size into the subroutine that returns the callback reference,we won't have acces to the variable."——“如果我们把$total_size的定义放在返回回调引用的子程序里的话,我们将无法访问这个变量。”?而且,为什么需要用一个没有任何意义的参数dummy去调用返回的匿名子程序才能获得最终的$total_size,而不是在匿名子程序中直接返回$total_size?这段代码应该怎样理解?
小弟初学perl,被这个问题困扰了很久,恳请各位老师不吝赐教,谢谢! |
|