perl help finding proper date format
I need some help trying to figure out how to format dates in perl. I have a working perl script, with a regular expression, that works fine if I use hard coded date strings like this:
my $mon = 'Aug';
my $day = '05';
my $year = '2010';
These vars are used in a regular expression like this:
if ($line =~ m/(.* $mon $day) \d{2}:\d{2}:\d{2} $year: ([^:]+):backup:/)
Now, I need to automate this date portion of the code and use current date systematically. I looked into perl localtime and tried using unix date and throw them into variables. I need to have the days of the week, single digit, be padded with '0'. As in today, 'Aug' '05' '2010' because the input file I am using for the regex has dates like this.
My 2nd try with the unix and formatting is returning numbers, but I need to have them be strings:
my $mon2=`date '+%b'`;
my $day2=`date '+%d'`;
my $year2=`date '+%Y'`;
My test code for playing with date formats:
#!/usr/local/bin/perl -w
use strict;
my $mon = 'Aug';
my $day = '05';
my 开发者_StackOverflow社区$year = '2010';
my $mon2=`date '+%b'`;
my $day2=`date '+%d'`;
my $year2=`date '+%Y'`;
print "$mon";
print "$day";
print "$year";
print "$mon2";
print "$day2";
print "$year2";
My Output:
Aug052010Aug
05
2010
I hate to break it to you, but you're reinventing the wheel. All this is implemented quite comprehensively in the DateTime distribution and the DateTime::Format:: family of classes:
use DateTime;
my $dt = DateTime->now;
print 'It is currently ', $dt->strftime('%b %d %H:%M:%S'), ".\n";
prints:
It is currently Aug 05 23:54:01.
精彩评论