Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

#!/usr/bin/perl while(<DATA>){ s/^\d\d//g; print $_; } __DATA__ 20070820 070223 20080929
How to check if the date is in format 'YYYYMMDD' and replace it with 'YYMMDD'. 20070820 is in YYYYMMDD, is to replaced with 070820. 070223 is already in the format YYMMDD, so I should not replace it. Please tell me how to replace it.

Replies are listed 'Best First'.
Re: date replace
by ikegami (Patriarch) on Dec 11, 2009 at 06:09 UTC
    s/^\d{2}(?=\d{6}$)//

    Remove the two digits at the start of the string if the rest of the string consists of 6 digits and possibly a newline.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: date replace
by bichonfrise74 (Vicar) on Dec 11, 2009 at 06:08 UTC
    Is this what you want?
    #!/usr/bin/perl use strict; while (<DATA>) { s/\d\d(.*)/$1/ if /\d{8}/; print; } __DATA__ 20070820 070223 20080929
Re: date replace
by AnomalousMonk (Archbishop) on Dec 11, 2009 at 11:35 UTC

    BTW – In the regex of the OP:

    s/^\d\d//g;

    The  /g regex modifier is pointless because the pattern is anchored at the start of the string, and there is never more than one of those.

    However, if the  /m modifier were used to allow  ^ to match after embedded newlines,  /g might make some sense.

    See discussions of g and m regex Modifiers in perlre and perlretut.

    Update: Slight wording changes.