i want to compare the current time and file creation time in Perl but both are in different format. localtime is in this format:
22116291110813630
and file creation time is
Today, December 29, 2008, 2:38:37 PM
How do i compare which one is greater and their difference?
Upvotes: 5
Views: 25292
Reputation: 2393
It's even easier than using stat() and time()/localtime().
my $diff = -M $filename;
The -M operator returns the "age" of the file (in days since the start of the program). It's documented under the -X functions or in perldoc -f -X
.
Upvotes: 16
Reputation: 323
These two functions are thanks to jimtut's answer. fileage prints the number of seconds as an integer, perfect for usage in a shell, of a file from when it was created. fileage is the answer to the above question, while dataage prints the same for the contents of a file as that's the answer I was looking for I'm sure these will both be useful.
function fileage {
perl -e 'printf "%i\n", 60 * 60 * 24 * -C "'"${1:?Must provide a file name}"'"'
}
function dataage {
perl -e 'printf "%i\n", 60 * 60 * 24 * -M "'"${1:?Must provide a file name}"'"'
}
Upvotes: 0
Reputation: 127628
If you want to compare values, you might want to use the number you got from localtime
in scalar context and the inode change time that you can get from stat
:
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks)
= stat($filename);
where:
0 dev device number of filesystem 1 ino inode number 2 mode file mode (type and permissions) 3 nlink number of (hard) links to the file 4 uid numeric user ID of file's owner 5 gid numeric group ID of file's owner 6 rdev the device identifier (special files only) 7 size total size of file, in bytes 8 atime last access time in seconds since the epoch 9 mtime last modify time in seconds since the epoch 10 ctime inode change time in seconds since the epoch (*) 11 blksize preferred block size for file system I/O 12 blocks actual number of blocks allocated
So you want field 9:
$mtime = ( stat $filename )[9];
$current_time = time;
$diff = $current_time - $mtime;
Upvotes: 14
Reputation: 98508
localtime
returns a list of values in list context. See the localtime documentation or perlcheat. In your example, it looks like those all mushed together. In scalar context, it returns a formatted string like Mon Dec 29 03:16:33 2008
. On most platforms, the file inode change time will be returned from stat
as a number of seconds since some epoch. You should be able to directly compare that to the result of time()
(not localtime()
).
Upvotes: 3