views:

717

answers:

5

What's the best way to do it?

EDIT: Originally the question was "How to do it without the DateTime module". I removed this restriction in order to make the question more general.

+2  A: 

UPDATE: Note that this answer was to the original question, which specifically excluded use of DateTime modules.

To get modified time

my $mtime = (stat $filename)[9];

This returns the last modify time in seconds since the epoch.

Then, to translate to date components, use localtime -

my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($mtime);

Note that localtime returns 0 for Jan, 1 for Feb, etc, and $year is the number of years since 1900, so 109 -> 2009.

Then to output in the format DDMMYY -

print substr('0'.$mday,-2), substr('0'.($mon+1),-2), substr($year+1900,-2);

So it's easier - and less error-prone - to simply use Date::Format if you can.

Ed Guiness
POSIX::strftime('%m%d%y', $mtime) is also easier and less error prone
ysth
A: 
use Date::Format;
print time2str("%d%m%y", (stat $filename)[9]);
Igor Oks
So modules are allowed now?
innaM
Isn't supported or isn't installed?
innaM
+7  A: 

See Time::Piece for more

use Time::Piece;
localtime((stat $filename)[9])->ymd;                # 2000-02-29
localtime((stat $filename)[9])->ymd('');                 # 20000229
localtime((stat $filename)[9])->dmy("");#is what you wanted



$perl -MTime::Piece -e 'print localtime(time)->dmy("")'
Berov
And it's core in 5.10, which is maybe relevant (since modules may be an issue here).
Telemachus
+4  A: 

Here's a reasonably straightforward method using POSIX (which is a core module) and localtime to avoid twiddling with the details of what stat returns (see Edg's answer for why that's a pain):

use POSIX qw/strftime/;

my @records;

opendir my $dh, '.' or die "Can't open current directory for reading: $!";

while (my $item = readdir $dh) {
    next unless -f $item && $item !~ m/^\./;
    push @records, [$item, (stat $item)[9]];
}

for my $record (@records) {
    print "File: $record->[0]\n";
    print "Mtime: " . strftime("%d%m%Y", localtime $record->[1]), "\n";
}
Telemachus
+7  A: 

If this is the only date formatting I need to do and don't need any date features for anything else, I just use POSIX (which comes with Perl):

use POSIX;

my $file = "/etc/passwd";

my $date = POSIX::strftime( 
             "%d%m%y", 
             localtime( 
                 ( stat $file )[9]
                 )
             );

Forget about -M if you aren't using relative time. Go directly to stat to get the epoch time.

brian d foy