Go Back   CodingForums.com > :: Server side development > Perl/ CGI

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-24-2002, 01:35 PM   PM User | #1
aweizd
New to the CF scene

 
Join Date: Sep 2002
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
aweizd is an unknown quantity at this point
number formats

hi,

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?

thx
aweizd is offline   Reply With Quote
Old 09-25-2002, 05:12 PM   PM User | #2
Mouldy_Goat
Regular Coder

 
Join Date: Jul 2002
Location: London, UK
Posts: 126
Thanks: 0
Thanked 0 Times in 0 Posts
Mouldy_Goat is an unknown quantity at this point
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:
Code:
#!/usr/bin/perl

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:
lalala2foobar
would stay the same.

If you wanted to change its behaviour so that the above would change to this:
lalala02foobar
You would need to change the regular expression to:
Code:
$data =~ s/(\d+)/sprintf("%.02d", $1)/eg;
Hope that helps.
Mouldy_Goat is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:25 AM.


Advertisement
Log in to turn off these ads.