【问题标题】:Getting modification time in perl on my MAC not working在我的 MAC 上的 perl 中获取修改时间不起作用
【发布时间】:2014-04-29 00:46:53
【问题描述】:

我有以下代码用于获取文件的修改时间。但它不起作用。无论我使用 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>

【问题讨论】:

    标签: macos perl stat ctime


    【解决方案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";
    

    希望有帮助!

    【讨论】:

    • 谢谢吉姆。我没有注意到我没有传递文件的完整路径。感谢您发现错误。
    • 没问题。也做了一百次。如果您对答案感到满意,请不要忘记“接受”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2017-12-25
    相关资源
    最近更新 更多