Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Using sprintf in regular expreession.

by johngg (Canon)
on Feb 02, 2022 at 22:22 UTC ( #11141087=note: print w/replies, xml ) Need Help??


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 (Sage) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11141087]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2023-02-05 23:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (33 votes). Check out past polls.

    Notices?