免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2485 | 回复: 3
打印 上一主题 下一主题

求教高手——一段perl代码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-09-29 18:55 |只看该作者 |倒序浏览
本帖最后由 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";

论坛徽章:
0
2 [报告]
发表于 2011-09-30 01:40 |只看该作者
Precisely because of File::Find, it's one of those weird balls of Perl (actually due to the underlying C programs, I'd guess)

find (\&wanted, "Directory") .... ' find() ' makes &wanted do all the work, and yet IGNORES all the return values from &wanted...

so the $callback can certainly have a return value, but just being ignored by ' find '

论坛徽章:
0
3 [报告]
发表于 2011-09-30 11:26 |只看该作者
回复 2# Kitaisky


    非常感谢,同时还有一个疑问
为什么If we stick the definition of $total_size into the subroutine that returns the callback reference, we won’t have access to the variable.?
是否应该按照Reference Counting引用计数理论来理解呢,如果是的话,具体应该怎样分析?
望不吝赐教。

论坛徽章:
0
4 [报告]
发表于 2011-09-30 16:05 |只看该作者
回复 3# perlearner


    同时,在File::Find的文档中也提到,find (\&wanted, "Directory")这种格式的用法中,\&wanted针对Directory中的每个条目进行递归搜索,每找到一个文件或目录,就对其采取\&wanted操作。但为什么直接返回$total_sizes += -s if -f,就无法在外部访问到$total_size变量了呢?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP