0

我有以下代码用于获取文件的修改时间。但它不起作用。无论我使用 stat 命令还是 -M 运算符,我都会收到错误消息,例如“使用未初始化的值……”或“无法在未定义的值上调用方法“mtime””,具体取决于我使用的方法。有什么建议么?我正在使用 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>
4

1 回答 1

1

use strict;在脚本的开头打开。你会发现你打电话的方式有问题statopen除非您出于其他原因需要该文件,否则不要。跳过整个 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";

希望有帮助!

于 2014-03-21T17:10:04.190 回答