我使用以下代码来获取文件的修改时间。但它不起作用。无论我使用stat命令还是-M运算符,我都会收到错误消息,如"使用未初始化的值…"或"无法对未定义的值调用方法"mtime",这取决于我使用的方法。有什么建议吗?我使用的是MAC操作系统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: $latestfilen";
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>
在脚本开始时打开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: $latestfilen";
print localtime(stat($latestfile)->mtime) . "n";
希望能有所帮助!