免费注册 查看新帖 |

Chinaunix

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

自己写了一个脚本,运行有问题,请大家帮忙看看 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-07-10 15:04 |只看该作者 |倒序浏览
作用。统计一个目录下,所有文件行数的总和。如果目录中还有目录,则递归查询,知道查到所有文件。



  1. #!/usr/local/bin/perl

  2. use strict;
  3. use vars qw/$count/;

  4. $count = 0;
  5. my $default_dir = $ENV{PWD};

  6. my $dir = $ARGV[0] || $default_dir;
  7. chomp $dir;

  8. get_dir($dir);
  9. print $count."\n";

  10. sub get_file {
  11.         my $file = shift;
  12.         open (FH,"$file") or die "Can't open the file:$!\n";
  13.         count_file("*FH");
  14.         close FH;
  15. }

  16. sub get_dir {
  17.         my $dir = shift;
  18.         opendir (DIR,"$dir") or die "Can't open dir:$!";
  19.         my @file = readdir(DIR);
  20.         closedir(DIR);
  21.         foreach (@file){
  22.                 if (-d $_){
  23.                         get_dir($_);
  24.                 }else{
  25.                         get_file($_);
  26.                 }
  27.         }
  28. }

  29. sub count_file {
  30.         my $FH = shift;
  31.         while (<FH>) {
  32.                 next if /^\s+$/;
  33.                 ++$count;
  34.         }
  35. }

复制代码


请大家指正,我是新手。程序运行时,过一段时间显示:
Out of memory during request for 4084 bytes, total sbrk() is 536793088 bytes!
Out of memory during request for 2052 bytes, total sbrk() is 536795136 bytes!
查看top信息。发现交换分区全部用完。

论坛徽章:
0
2 [报告]
发表于 2006-07-10 16:17 |只看该作者
原帖由 condor_P 于 2006-7-10 15:04 发表


  1. 1  sub get_dir {
  2. 2        my $dir = shift;
  3. 3        opendir (DIR,"$dir") or die "Can't open dir:$!";
  4. 4         my @file = readdir(DIR);
  5. 5        closedir(DIR);
  6. 6         foreach (@file){
  7. 7             if (-d $_){
  8. 8                 get_dir($_);
  9. 9            }else{
  10. 10              get_file($_);
  11. 11          }
  12. 12     }
  13. 13 }
复制代码


Hallo,

the wrong point is at if (-d $_) { ...
reddir() reads relative filename and put it (without fullpath) in the array @file!
You should check $_ with fullpath!!!
i.e.:

  1. 6      foreach (@file) {
  2.             next if $_ eq '.' or $_ eq '..';    // skip it
  3. 7          my $fullfilename = "$dir/$_";
  4. 8          if (-d $fullfilename) {
  5. 9              get_dir($fullfilename);
  6. 10        } else {  
  7. 11            get_file($fullfilename);
  8. 12        }
  9. 13    }
复制代码


Read more about perldoc perlfunc =>relative opendir(), readdir()

Best,
    ulmer

--------
Just 4 Fun

论坛徽章:
0
3 [报告]
发表于 2006-07-10 17:10 |只看该作者
非常感谢您的帮助,按照您的方法,我成功了。

[ 本帖最后由 condor_P 于 2006-7-10 17:17 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP