Possibly one of these methods will help? (From perldoc perlfaq5) {see update below}:
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 whate
+ver.
)
| # or:
\G\d{3} # after the last group, get three digits
(?=\d) # but they have to have more digits after the
+m.
)/$1,/xg;
Update: In 352970, tachyon points out that the commify subroutine in the FAQ is pretty inefficient -- "it backtracks to do the job and also chokes on things like $1000 or 'string 123456'." I didn't know this prior to tachyon's post, so I'd suggest using the subroutine from the Perl cookbook (shown in 352970 as well as below in injunjoel's post. Learn something new every day... |