http://qs1969.pair.com?node_id=11141087


in reply to Using sprintf in regular expreession.

Rather than using regular expressions and substitution you could split on hyphens into a list which you then slice into the order required. Pass the re-ordered items through a map in which you apply the sprintf and then join it all up again. Perhaps a bit more long winded but, to my eyes, a little easier to see what's going on.

johngg@abouriou:~/go$ perl -Mstrict -Mwarnings -E 'say q{}; my $date = q{3-15-1932}; $date = join q{-}, map { sprintf q{%02d}, $_ } ( split q{-}, $date )[ 2, 0, 1 ]; say $date;' 1932-03-15

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Using sprintf in regular expreession.
by LanX (Saint) on Feb 02, 2022 at 23:58 UTC
    > Perhaps a bit more long winded

    IMHO, you are overcomplicating it. sprintf can take a list of values, no need for a map.

    It can even rearrange the order, tho I prefer the slice here.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      TIMTOWTDI

      DB<23> $date = "3-15-1932" #### split and slice DB<24> printf "% 4d-%02d-%02d", (split /-/, $date)[2,0,1] 1932-03-15 #### match list DB<25> printf "% 4d-%02d-%02d", ($date =~ /(\d+)-(\d+)-(\d+)/ )[2,0, +1] 1932-03-15 #### reorder printf with 3$ DB<26> printf "%3\$ 4d-%02d-%02d", split /-/, $date 1932-03-15 #### classic DB<27> printf "% 4d-%02d-%02d",$3,$1,$2 if $date =~ /(\d+)-(\d+)-(\d ++)/ 1932-03-15

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery