LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1555|回复: 3

perl新手遇到读取文件问题

[复制链接]
发表于 2010-4-13 01:39:09 | 显示全部楼层 |阅读模式
想要通过命令行参数传一个目录
然后把每个文件名和mtime信息存入哈希表里
可是mtime总是读不到
下面是程序:
#!/usr/bin/perl -w
use strict;
#use warnings;
my $directory ;
my $num=@ARGV;
if ($num ==0) {die "please input the directory through the command line !\n";
}
else { $directory = shift(@ARGV);}
if (!-e $directory) {
        print "the directory is not exist !\n";
        exit;
}

print "-------start monitoring $directory -----(press ctrl+c to halt)--------\n";

my %file;             #储存所有(文件名,mtime)
my $size;

#while(1){
       
        &getstat();
       
       

sub getstat{
        opendir DIR,$directory or die "cannot open the directory!\n";

        my %file=();
        my @files= readdir DIR;
        print "@files\n";
        foreach my $i (@files) {
                my @stat= stat $i;
                print "@stat\n";
                my $mtime= $stat[9];
                print $mtime;
                $size= $stat[7];
                $file{$i}= $stat[9];
        }
       
        #return %file;
        foreach my $key (sort keys %file){
        my $value = $file{$key};
        print "$key => $value\n";}

}

#}

为什么只能读到. 和..的stat信息
其余的文件都为空??
发表于 2010-4-14 13:31:36 | 显示全部楼层
我猜想,如果你是
  1. opendir DIR,"/tmp"
复制代码
假设/tmp下面有文件file1
你readdir DIR返回的是file1
然后是
  1. stat "file1"
复制代码
可是当前目录下并没有file1,它在/tmp下面。于是上面的代码当然得不到信息了。

readdir返回的是那个目录下的文件名,你需要把它和目录名拼起来得到完整的路径,或者stat之前chdir过去
回复 支持 反对

使用道具 举报

 楼主| 发表于 2010-4-16 18:43:16 | 显示全部楼层
恩!已经解决了
确实是你说的那样 要带上路径
谢谢啦
回复 支持 反对

使用道具 举报

发表于 2010-4-17 10:50:03 | 显示全部楼层
如果你要监视目录的变化,建议用用 pyinotify
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表