Question

I have following code that I am using to get modification time of a file. But it is not working. Whether I use stat command or -M operator, I am getting error messages like "Use of uninitialized value…" or "Can't call method "mtime" on an undefined value" depending on which method I use. Any suggestions? I am using MAC OS v10.8.5. I swear that the -M option worked yesterday few times but since then it has stopped working. I am flummoxed.

<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>
Was it helpful?

Solution

Turn on use strict; at the beginning of your script. You'll find that there's a problem with the way you're calling stat. Unless you need to open the file for some other reason, don't. Skip the whole FH stuff.

But, your bigger problem is you're trying to stat a file but you're not giving the full path to the file. chdir to the folder (or pass the full path to stat).

This works for me:

#!/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";

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top