Here's an explicit way using length and treating the 'number' like a string:
use strict; use warnings; my $number = 123; my $pad = 9 - length $number; $number = '0' x $pad . $number; print "$number\n";
The sprintf approach is tidier:
use strict; use warnings; my $number = 123; $number = sprintf "%09u", $number; print "$number\n";
Update: When only a RE will do, here's a regex approach with the s/// operator. It's not as clean as the sprintf approach, but you may have your reasons for using it:
$number = 123; $number =~ s/(\d{0,9})$/'0' x (9 - length $1) . $1/e; print "$number\n";
Update 2: It's been said that it can't be done with a m// regex, and I suppose for a pure regular expression implementation that's true. But I couldn't just leave it at that, so here's a m// regex approach that works by taking liberties with what is being bound to the m// operator:
my $number = 123; print "$number\n" if ($number) = ( '0' x 9 . $number ) =~ m/(\d{9})$/;
Dave
In reply to Re: adding characters via a regular expression
by davido
in thread adding characters via a regular expression
by jwking
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |