Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zero padded integer with perl regex substitution

I would like to do a zero padded integer with regex substitution. I have for example the following string:

my $string = '3-7+9-15';

and want for output:

03-07+09-15

i know i could use sprintf, but i must first retrieve each integer do the sprintf and then re-join the integers into a string :(

i would like to do it in one pass with a regex substitution. is it possible ?

like image 445
skualito Avatar asked Jan 29 '23 16:01

skualito


1 Answers

I would choose to use sprintf in combination with a regex substitution

use strict;
use warnings 'all';
use feature 'say';

my $s = '3-7+9-15';
$s =~  s{(\d+)}{ sprintf '%02d', $1 }ge;
say $s;

output

03-07+09-15
like image 115
Borodin Avatar answered Feb 01 '23 23:02

Borodin