在我的MAC上的perl修改时间不起作用

时间:2014-03-21 15:03:37

标签: macos perl stat ctime

我有以下代码用于获取文件的修改时间。但它没有用。无论我使用stat命令还是-M操作符,我都会收到错误消息,例如“使用未初始化值...”或“无法调用方法”mtime“on undefined value”,具体取决于我使用的方法。有什么建议?我使用的是MAC OS v10.8.5。我发誓-M选项昨天工作了几次,但从那时起它就停止了工作。我很沮丧。

<code>
#!/usr/bin/perl
use POSIX qw(strftime);
use Time::Local;
use Time::localtime;
use File::stat;
use warnings;

$CosMovFolder = '/Logs/Movies';
#sorting files based on modification date
opendir (DIR, $CosMovFolder);
@moviedir=readdir(DIR);
#$file1modtime = -M $moviedir[1]; #it works here but doesn't work if used after the 
sort line below. Why?

closedir(DIR);  
#sorting files by modification dates
@moviedir = sort { -M "$CosMovFolder/$a" <=> -M "$CosMovFolder/$b" } (@moviedir); 
#$file1modtime = -M $moviedir[1]; #tried this, not working.  same uninitialized value error message

$latestfile = $moviedir[1];
print "file is: $latestfile\n";
open (FH,$latestfile);

#$diff_mins = (stat($latestfile))[9];  #didn't work, same uninitialized value error message
my $diff_mins = (stat(FH)->mtime); # Can't call method "mtime" on an undefined value error message
print $diff_mins,"\n";
close FH
</code>

1 个答案:

答案 0 :(得分:1)

在脚本开头打开use strict;。您会发现您调用stat的方式存在问题。除非您出于其他原因需要open该文件,否则不要这样做。跳过整个FH的东西。

但是,更大的问题是您尝试stat文件,但是您没有提供文件的完整路径。 chdir到文件夹(或传递到stat的完整路径。)

这对我有用:

#!/usr/bin/perl
use strict;
use warnings;
use File::stat;

my $CosMovFolder = '/Logs/Movies';
chdir($CosMovFolder) or die $!;
#sorting files based on modification date
opendir (DIR, $CosMovFolder);
#Grab all items that don't start with a period.
my @moviedir = grep(/^[^\.]/, readdir(DIR));
#$file1modtime = -M $dir[1]; # tried this, not working.  same uninitialized value error message
closedir(DIR);  
@moviedir = sort { -M "$CosMovFolder/$a" <=> -M "$CosMovFolder/$b" } (@moviedir); #sorting files by modification dates
my $latestfile = $moviedir[0];
print "file is: $latestfile\n";
print localtime(stat($latestfile)->mtime) . "\n";

希望有所帮助!