tags:

views:

164

answers:

3

How do I do the following conversion in regex in Perl?

British style   US style
"2009-27-02" => "2009-02-27"

I am new to Perl and don't know much about regex, all I can think of is to extract different parts of the "-" then re-concatenate the string, since I need to do the conversion on the fly, I felt my approach will be pretty slow and ugly.

+10  A: 
use strict;
use warnings;
use v5.10;

my $date = "2009-27-02";
$date =~ s/(\d{4})-(\d{2})-(\d{2})/$1-$3-$2/;
say $date;
David Dorward
Wow, this is fast David and I love your solution. Neat, thanks!
John
By the way, I never know say is a perl keyword, was it introduced recently?
John
Yes, backported from Perl 6 into Perl 5.10 (hence the `use v5.10` line here). See `perldoc feature` http://perldoc.perl.org/feature.html#IMPLICIT-LOADING
ephemient
say was introduced in perl 5.10 but you need to `use v5.10` to enable it (like print but it automatically adds newlines).
ternaryOperator
@John: say is a Perl built-in function which was added in version 5.10 (released about 2 years ago). See also http://perldoc.perl.org/5.10.0/perl5100delta.html
toolic
@toolic: thanks for the link. Per the doc, say() wraps print with a new line, which is neat.
John
+4  A: 

You can also use Date::Parse for reading and converting dates. See this question for more information.

James Thompson
+4  A: 

You asked about regex, but for such an obvious substitution, you could also compose a function of split and parse. On my machine it's about 22% faster:

my @parts = split '-', $date;
my $ndate = join( '-', @parts[0,2,1] );

Also you could keep various orders around, like so:

my @ymd = qw<0 2 1>;
my @mdy = qw<2 1 0>;

And they can be used just like the literal sequence in the first section:

my $ndate = join( $date_separator, @date_parts[@$order] );

Just an idea to consider.

Axeman
I definitely could, and I wrote very much the same code as yours. However, I feel like I should choose regex as it is neat and improves readability (considering I am using perl). Thanks anyway.
John
@John: well, it could be faster, so it answers the "slow and ugly" part. And, as I showed, can be expanded to be a bit more flexible in approach.
Axeman
@John: I dunno, I think `$date = join '-', reverse split /-/, $date;` is at least as clear as the regex solution.
ephemient