I'd like to re-arrange a timestamp with a Perl regex with the least code possible. The original format of the time stamp is as follows:
2011/12/29 20:19:45
All I need to do is convert it so that the year at the front instead comes after the month/date as follows:
12/29/2011 20:19:45
I was able to achieve this with the 3 lines of code below. I'm just wondering if there is a way to do this with less code. In particular I tried to do away with the middle line saving $1 into an intermediate variable, and specifying $1 from the first substitution directly in the regex for the second substitution, but this resulted in the error: "Use of uninitialized value $1 in concatenation (.) or string."
If the second line cannot be gotten rid of, then it would seem like this can't be gotten down to one line either?
#my $ts = '2011/12/29 20:19:45'; #input to a subroutine
$ts =~ s/^(\d{4})\///;
my $year = $1;
$ts =~ s/ /\/$year /;
Here are you go:
$ts =~ s|^(\d{4})/(\d{2})/(\d{2})(.+)$|$2/$3/$1$4|;
Please note that the above expression expects timestamps having exactly 2 digits for months and days and 4 digits for years. But you can make it even shorter yet more reliable:
$ts =~ s|^(\d+)/(\d+)/(\d+)(.+)$|$2/$3/$1$4|;
This one will handle timestamps like 1/12/98 12:34:56 properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With