Perl FAQ 4.34: How can I print out a number with commas into it?

Perl FAQ 4.34

How can I print out a number with commas into it?

This one will do it for you:

sub commify {
    local($_) = shift;
    1 while s/^(-?\d+)(\d{3})/$1,$2/;
    return $_;
} 

$n = 23659019423.2331;
print "GOT: ", &commify($n), "\n";

GOT: 23,659,019,423.2331

The reason you can't just do

    s/^(-?\d+)(\d{3})/$1,$2/g;
Is that you have to put the comma in and then recalculate anything. Some substitutions need to work this way. See the question on expanding tabs for another such.


Other resources at this site: