How do I get a file's timestamp in perl?

If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the -M, -A, or -C file test operations as documented in perlfunc. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See perlport for details. To retrieve the "raw" time in seconds since the epoch, you would call the stat function, then use localtime(), gmtime(), or POSIX::strftime() to convert this into human-readable form.

Here's an example:

    $write_secs = (stat($file))[9];
    printf "file %s updated at %s\n", $file,
	scalar localtime($write_secs);
If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later):

    # error checking left as an exercise for reader.
    use File::stat;
    use Time::localtime;
    $date_string = ctime(stat($file)->mtime);
    print "file $file updated at $date_string\n";
The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See perllocale for details.
Back to perlfaq5