- 论坛徽章:
- 0
|
本帖最后由 perlearner 于 2011-09-30 11:26 编辑
求教各位高手,在《InterMediatePerl》中这段文字和代码怎样理解?
为什么不能在闭包中直接返回 "return $total_size += -s if -f;",而是要用if控制结构来判断是否有参数呢?
How would we get the total size of all found files from the callback? Earlier, we were able to do this by making $total_size visible. If we stick the definition of $total_size into the subroutine that returns the callback reference, we won’t have access to the variable. But we can cheat a bit. For one thing, we can determine that we’ll never call the callback subroutine with any parameters, so, if the subroutine receives a parameter, we make it return the total size:
use File::Find;
sub create_find_callback_that_sums_the_size {
my $total_size = 0;
return sub {
if (@_) { # it’s our dummy invocation
return $total_size;
} else { # it’s a callback from File::Find:
$total_size += -s if -f;
}
};
}
my $callback = create_find_callback_that_sums_the_size( );
find($callback, ‘bin’);
my $total_size = $callback->(‘dummy’); # dummy parameter to get size
print "total size of bin is $total_size\n"; |
|