How to check timestamp of a file using Perl

How to check timestamp of a file using Perl

You can use the built-in module File::stat (included as of Perl 5.004).

Say the file handle is $fh. Calling stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):


perl

  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 since the epoch
  9 mtime last modify time since the epoch
  10 ctime inode change time (NOT creation time!) since the epoch
  11 blksize preferred block size for file system I/O
  12 blocks actual number of blocks allocated

The 9th element in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can compute the local time:

 my $epoch_timestamp = (stat($fh))[9];
 my $timestamp = localtime($epoch_timestamp);

If you use Time::localtime module, the code willl look better:

 use File::stat;
 use Time::localtime;
 my $timestamp = ctime(stat($fh)->mtime);

 

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *