I'm working on a script which shows the age of an existing file and then automatically delete it after about 4 hours of being there (presumed maintenance window). I've been trying to test my output with the stat
function in Perl. We have multiple boxes, some running Linux and Solaris, so this is the most portable way to do it. I'm trying to get epoch time.
use File::stat;
$file = "samplefile";
$mtime = (stat($file))[9];
if (!defined $file){
print "No file specified\n";
exit 1;
}
printf("%d", @mtime);
I know stat()
returns a @_
, so I tried to change my datatype to this. But it keeps coming back saying that mtime
has not been initialized. Why does it say that?
You print the contents of @mtime
, but you placed the result in $mtime
. Always use use strict; use warnings;
. It would have found your problem.
Your code should look like one of the following:
Without File::stat (stat
returns a list):
use strict;
use warnings;
my $file = "samplefile";
my $mtime = (stat($file))[9];
die "Can't stat file: $!\n" if !defined($mtime);
printf("%d\n", $mtime);
(EXPR)[9]
returns the 10th element of the list EXPR
returns, or undef if the list isn't that long. This is a scalar you assigned to $mtime
, not @mtime
.
With File::stat (stat
returns an object):
use strict;
use warnings;
use File::stat;
my $file = "samplefile";
my $stat = stat($file);
die "Can't stat file: $!\n" if !$stat;
printf("%d\n", $stat->mtime);