免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: rocenting
打印 上一主题 下一主题

perl下迭代器的"示范"代码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-24 13:00 |显示全部楼层 |倒序浏览
原本是帮一个朋友面试而写的,顺便公开出来,请多指教。

  1. #!/\perl/\bin
  2. # Copyright (C) 2008 luo chuanting<[email]rocenting@gmail.com[/email]>
  3. # Release under GPL license

  4. use strict;

  5. my $test_switch = 1;
  6. main();

  7. sub main {
  8.         if ($test_switch == 1) {
  9.                 test_1();
  10.                 test_2();
  11.         }
  12. }

  13. sub gen_iterator_1 {
  14.         my $count = shift @_;

  15.         while ($count < 10) {
  16.                 $count++;
  17.                 return (sub {gen_iterator_1($count)}, [$count, "gen_iterator_1"])
  18.         }

  19.         return;
  20. }

  21. sub cal_value {
  22.         my $next_fn = shift @_;
  23.         my $e;

  24.         while (($next_fn, $e) = $next_fn->()) {
  25.                 print "$e->[1]: $e->[0]\n";
  26.         }
  27. }

  28. sub test_1 {
  29.         my $next_fn = sub {gen_iterator_1(0);};
  30.         my $e;

  31.         while (($next_fn,$e ) = $next_fn->()) {
  32.                 print "$e->[1]: $e->[0]\n";
  33.         }
  34. }


  35. sub test_2 {
  36.         my $count = 5;

  37.         sub gen_iterator_2 {
  38.                 while ($count < 10) {
  39.                         $count++;
  40.                         return (\&gen_iterator_2, [$count, "gen_iterator_2"])
  41.                 }
  42.                 return;
  43.         }

  44.         cal_value(\&gen_iterator_2);
  45. }
复制代码

[ 本帖最后由 rocenting 于 2008-12-24 13:06 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-12-24 13:36 |显示全部楼层
原帖由 cobrawgl 于 2008-12-24 13:29 发表
lz 是不是会用 python 啊



怎么会这样说呢

论坛徽章:
0
3 [报告]
发表于 2008-12-24 15:43 |显示全部楼层
原帖由 MMMIX 于 2008-12-24 15:12 发表

shift @_; 看得我别扭死了



我感觉不写@_才很别扭,呵呵。

很多时候不写,别人会问为什么???,权当注释。

论坛徽章:
0
4 [报告]
发表于 2008-12-24 15:45 |显示全部楼层
原帖由 MMMIX 于 2008-12-24 15:14 发表
说说实现方面的问题,递归调用显然不是个好主意,用 closure 会好很多。



test_1
是递归

test_2
是closure

论坛徽章:
0
5 [报告]
发表于 2008-12-24 16:33 |显示全部楼层
原帖由 MMMIX 于 2008-12-24 16:20 发表

是我看岔了,两个都是 closure。


多谢指教

其实你不说之前,我很少关注closure这些概念

只感觉Perl的ref很好用

论坛徽章:
0
6 [报告]
发表于 2008-12-24 16:55 |显示全部楼层
原帖由 flw 于 2008-12-24 16:30 发表

对,适度使用“惯用语”,会让代码更地道,让内行人看着更亲切易懂。



开个玩笑

现在国内流行山寨

论坛徽章:
0
7 [报告]
发表于 2008-12-24 17:42 |显示全部楼层
原帖由 smonkey0 于 2008-12-24 15:44 发表
Effective_Perl_Programming.chm



谢啦,下了浏览了一下,还不错!

你们所说的"习惯语"就是Idiomatic吧。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP