http://www.perlmonks.org?node_id=219306

Tanalis has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I'm writing a reporting script at the moment that needs to handle very large numbers and output them in an easy-to-read way. I've worked out a way to "commify" a number - taking, for example 1234567890 and returning 1,234,567,890.

The code that does this involves a regexp and a while loop, and while it works fine, it's not particularly clean or efficient:

sub commify { my $number = shift; while ($number =~ s/(^-*\d*\d)(\d{3})/$1,$2/) { ; } return $number; }

I'm interested to know if there's a "simpler" way to do this - ideally getting rid of the super-hideous while loop. I should point out I've tried adding /g to the regexp, but this doesn't have the same effect as the while loop - the pattern matches the entire string each time, and simply replaces the last 3 digits with a comma followed by the digits.

Any ideas/suggestions would be useful.

Thanks ..
-- Foxcub