in reply to Generating a format template for a date

Not particularly elegant, but fairly clean:
sub convert_format { my $format = shift; # If we have a 4 digit year $format =~ s/9999/YYYY/; # Two cases: if ($format =~ /^Y/) { # Month first $format =~ s/99/MM/; $format =~ s/99/DD/; } else { # Day first $format =~ s/99/DD/; $format =~ s/99/MM/; } # Handle two digit year $format =~ s/99/RR/; return $format; }

Replies are listed 'Best First'.
Re^2: Generating a format template for a date
by davidrw (Prior) on Oct 13, 2006 at 17:52 UTC
    Extension of that idea, ditching the conditionals (implicitly burying them in the regex's):
    while(<DATA>){ s/9999/YYYY/; # 4-char year first s/(?<=[^9])99(?=[^9])/MM/; # month is always in the middle s/(?<!YYYY.{4})99$/RR/; # 2-char year is always at end, and won +'t have a 4-char year already s/99/DD/; # the remaining 2-chars will be the day print; } __DATA__ 99/99/9999 99/99/99 99-99-9999 99-99-99 99:99:9999 99:99:99 99+99+9999 9999-99-99 9999:99:99 9999+99+99
      Nice! Doing multiple subs on the same target is something which looks nicer using the implicit $_.

      I definitely need to read up on my extended regexps though, those look-ahead/behind assertions are gnarly, dude.