Dave
Dave

Reputation: 19110

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.

Upvotes: 0

Views: 70

Answers (2)

GMB
GMB

Reputation: 222432

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.

Upvotes: 2

Grinnz
Grinnz

Reputation: 9231

You can use the core File::stat to get a much nicer interface to the stat fields.

use strict;
use warnings;
use File::stat;
my $stat = stat($filename) or die "stat $filename failed: $!";
my $mtime = $stat->mtime;

Upvotes: 3

Related Questions