John
John

Reputation: 221

How can I reorder substrings in a string?

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.

Upvotes: 3

Views: 3124

Answers (3)

Axeman
Axeman

Reputation: 29844

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.

Upvotes: 5

James Thompson
James Thompson

Reputation: 48162

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

Upvotes: 4

Quentin
Quentin

Reputation: 943165

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;

Upvotes: 14

Related Questions