Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Formatting with sprintf

by LanX (Saint)
on Nov 10, 2015 at 01:05 UTC ( [id://1147316]=note: print w/replies, xml ) Need Help??


in reply to Formatting with sprintf

you want this
DB<150> sprintf "%d-%d-%d-%d", ('1234567890123456' =~ /(....)/g) => "1234-5678-9012-3456"

or this

DB<151> sprintf "%d%d%d%d-%d%d%d%d-%d%d%d%d-%d%d%d%d", split //, '12 +34567890123456' => "1234-5678-9012-3456"

But I'd rather prefer this

DB<153> join "-", ('1234567890123456' =~ /(....)/g) => "1234-5678-9012-3456"

TIMTOWTDI ... depends if you always make sure that the input is 16 characters long.

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

update

kennethk++ msged me that leading 0 are a problem in the first approach

DB<160> sprintf "%d-%d-%d-%d", ('0123456789012345' =~ /(....)/g) => "123-4567-8901-2345"

this would fix it

DB<161> sprintf "%04d-%04d-%04d-%04d", ('0123456789012345' =~ /(.... +)/g) => "0123-4567-8901-2345"

but honestly, I doubt I would stick with this approach.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-16 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found