* Tong * said:
Hi,
Is any Perl modules that can translate number like 10987654321 into
clearer to read string 10,987,654,321? and back?
I don't know what this kind of transformation called, so I don't know how
to search. thanks.
Hmmm, number and commas
what if I try
perldoc -q commas
Found in /apps/perl/5.9.1/lib/5.9.1/pod/perlfaq5.pod
How can I output my numbers with commas added?
This subroutine will add commas to your number:
sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
This regex from Benjamin Goldberg will add commas to
numbers:
s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
It is easier to see with comments:
s/(
^[-+]? # beginning of number.
\d{1,3}? # first digits before first comma
(?= # followed by, (but not included
in the match) :
(?>(?:\d{3})+) # some positive multiple of three
digits.
(?!\d) # an *exact* multiple, not x * 3
+ 1 or whatever.
)
| # or:
\G\d{3} # after the last group, get three
digits
(?=\d) # but they have to have more
digits after them.
)/$1,/xg;