Warm tip: This article is reproduced from serverfault.com, please click

How can I get the local time modification of a file with File::stat in perl?

发布于 2020-11-30 13:43:23

How can I get the file modification time formatted in local time?

By doing this:

use File::stat;
use Time::Piece;

my $format = '%Y%m%d%H%M';

print Time::Piece->strptime(stat($ARGV[0])->mtime, '%s')->strftime($format);

I get 202011301257 for a file that was saved at Nov 30 13:57 in my local time (GMT+01:00).

Since I can do

print localtime $file->stat->mtime;

and

print localtime->strftime($format)

I'd like to do something like

print (localtime stat($file)->mtime)->strftime($format);

Which throws

Can't locate object method "mtime" via package "1" (perhaps you forgot to load "1"?) 

Any advice?

Questioner
simone
Viewed
11
Shawn 2020-12-01 02:36:59

I'd like to do something like

print (localtime stat($file)->mtime)->strftime($format);

Very close! Your first parenthesis is in the wrong spot:

#!/usr/bin/env perl
use warnings; # Pardon the boilerplate
use strict;
use feature 'say';
use File::stat;
use Time::Piece;

my $format = '%Y%m%d%H%M';
say localtime(stat($ARGV[0])->mtime)->strftime($format);