Reputation: 5221
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?
Upvotes: 1
Views: 595
Reputation: 385655
Always use use strict; use warnings;
. It would have caught the problem:
print (...) interpreted as function at a.pl line 6.
You have the following
print ( localtime ... )->strftime($format);
Because the space between print
and (
is meaningless, the above is equivalent to the following:
( print( localtime ... ) )->strftime($format);
The problem is that you are using ->strftime
on the result of print
. The problem goes away if you don't omit the parens around print
's operands.
print( ( localtime ... )->strftime($format) );
Alternatively, not omitting the parens localtime
's args would allow you to remove the parens causing the problem.
print localtime( ... )->strftime($format);
Upvotes: 1
Reputation: 52344
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);
Upvotes: 2