View Full Version : number formats

09-24-2002, 02:35 PM

i have a txt file with numbers in it. i want to change all the one digit number to two digit format. e.g "5" -> "05" how do i do this?


09-25-2002, 06:12 PM
If you want to do formatting on a number/string the functions to use are printf and sprintf, the difference being that sprintf returns a formatted string whilst printf prints a formatted string.

Here's some example code to help with your problem:


open (DATA, "data.tst") || die "Couldn't open data.tst for reading: $!";
while (<DATA>) {
$data .= $_;
close DATA;

$data =~ s/\b(\d+)\b/sprintf("%.02d", $1)/eg;

open (DATA, ">data.tst") || die "Couldn't open data.tst for writing: $!";
print DATA $data;
close DATA;

print "Done!\n";

Where data.tst is the file with your numbers in.
The key code here is the regular expression, it works like this:
-match a word boundary
-match one or more digits (save for later use)
-match another word boundary
and replace this with a zero-padded form of the number of length 2 digits minimum, so 1 would become 01, 5 would become 05 and anything of 2 digits or more would stay as it is.

This will only match numbers that are on their own, i.e. this:
would stay the same.

If you wanted to change its behaviour so that the above would change to this:
You would need to change the regular expression to:

$data =~ s/(\d+)/sprintf("%.02d", $1)/eg;

Hope that helps.