Fixing dates


In the input we get dates like this 2010-7-5 but we would like to make sure we have two digits for both days and months: 2010-07-05


examples/regex-perl/date.pl
#!/usr/bin/perl
use strict;
use warnings;

sub fix_date {
    my $str = shift;
    $str =~ s/-(\d)\b/-0$1/g;
    return $str;
}


my %dates = (
    '2010-7-5'   => '2010-07-05',
    '2010-07-5'  => '2010-07-05',
    '2010-07-05' => '2010-07-05',
    '2010-7-15'  => '2010-07-15',
);

use Test::More;
plan tests => scalar keys %dates;

foreach my $in (sort keys %dates) {
    my $result = fix_date($in);

    is $result, $dates{$in}, $in;

#    print  "      old: $in\n";
#    print  "      new: $result\n";
#    print  " expected: $dates{$in}\n\n";
}

      old: 2010-07-05  
      new: 2010-07-05
 expected: 2010-07-05

      old: 2010-07-5   
      new: 2010-07-05
 expected: 2010-07-05

      old: 2010-7-15   
      new: 2010-07-15
 expected: 2010-07-15

      old: 2010-7-5    
      new: 2010-07-05
 expected: 2010-07-05



1..4
ok 1 - 2010-07-05
ok 2 - 2010-07-5
ok 3 - 2010-7-15
ok 4 - 2010-7-5


date.pl .. ok
All tests successful.
Files=1, Tests=4,  0 wallclock secs ( 0.05 usr +  0.00 sys =  0.05 CPU)
Result: PASS