Search code examples
perldatetimestamplast-modified

How do I get the last modified date of a directory?


I'm using 5.16.3. How do I get the last modified timestamp of a directory? With a file, I can run

    my $deployFile = "$jbossHome/standalone/deployments/$artifactId.$packaging";
    open my $fh, '>', $deployFile or die("File does not exist.");
    my $mtime = (stat ($fh))[9]; 

I tried this logic with a directory,

my $mtime = stat("$jbossHome/standalone/deployments/$artifactId.$packaging");

but the result is always

Thu Jan  1 00:00:01 1970

even though I can tell on the server that the last modified time stamp of the directory is this weekend.


Solution

  • This :

    my $mtime = stat("$jbossHome/standalone/deployments/$artifactId.$packaging");
    

    Should be written as :

    my $mtime = (stat("$jbossHome/standalone/deployments/$artifactId.$packaging"))[9];
    

    See perldoc stat.

    stat EXPR returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR.

    In the resulting list, mtime in 10th position (index 9).

    And also :

    In scalar context, stat returns a boolean value indicating success or failure

    So in your code, where you evaluate in scalar context, the mtime variable is assigned a value of 1. When interpretef as a Unix timestamp, this means 1 second after January 1st, 1970.