For integers, one can avoid reverse as well as the repeated
substr derivation of the remaining string in the loop:
sub commafy_int
{
my $n = shift;
length($n) > 3 or return $n;
my $l = length($n) - 3;
my $i = ($l - 1) % 3 + 1;
my $x = substr($n,0,$i) . ',';
while ( $i < $l )
{
$x .= substr($n,$i,3) . ',';
$i += 3;
}
$x . substr($n,$i)
}
Not using reverse also makes it much easier to convert this to work
on floats (i.e. strings containing a decimal separator,
'.').
To do so, simply replace any
length calls above with
index($n.'.','.').