From: PerlFAQ Server on
This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at .


5.14: How can I output my numbers with commas added?

(contributed by brian d foy and Benjamin Goldberg)

You can use Number::Format to separate places in a number. It handles
locale information for those of you who want to insert full stops
instead (or anything else that they want to use, really).

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:


It is easier to see with comments:

^[-+]? # beginning of number.
\d+? # 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.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in