[oclug] Quick Regexp question
Glenn Jackman
glennj at ncf.ca
Mon Nov 3 01:35:24 EST 2003
On 2003-11-02 23:29, Paul Faure wrote:
> How do I convert 1234567 to 1,234,567 in perl?
> So far I got
> $vol=~s/(\d{3})/,$1/g;
> But that creates ,123,4567
> That would be fine if it started searching from right to left instead of
> left to right.
You need to do it in a while loop: repeatedly, look for some digits
followed by 3 digits, and insert a comma in between:
sub commify {
my $n = shift;
while ($n =~ /^([-+]?\d+)(\d{3}.*)/) {$n = "$1,$2"}
return $n;
}
$vol = commify($_);
See: perldoc -q commas
--
Glenn Jackman
NCF Sysadmin
glennj at ncf.ca
More information about the OCLUG
mailing list