Another option is:
sub commify {
my $text = shift;
1 while $text =~ s/ ( \d ) ( \d{3} ) (\D|\z) /$1,$2$3/xms;
return $text;
}
When it comes to deciding which is faster, the Benchmark module is very useful.
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark;
sub your_commify {
my $text = reverse 100000000;
$text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
return scalar reverse $text;
}
sub my_commify {
my $text = 100000000;
1 while $text =~ s/ ( \d ) ( \d{3} ) (\D|\z) /$1,$2$3/xms;
return $text;
}
timethese(
-10,
{
'yours' => \&your_commify,
'mine' => \&my_commify,
}
);
Runing this gives:
~$ ./benchmark.pl
Benchmark: running mine, yours for at least 10 CPU seconds...
mine: 10 wallclock secs (10.01 usr + 0.01 sys = 10.02 CPU) @ 111456.89/s (n=1116798)
yours: 11 wallclock secs (10.04 usr + 0.00 sys = 10.04 CPU) @ 250092.33/s (n=2510927)
Looks like yours is ~2.25 times faster! (When using the "at least 10 CPU seconds" mode you have to check the values of "n" used.)
So it looks like you have to keep searching... but remember to use Benchmark!