Home > commafy

commafy

2nd January 2006

Perl offers many ways to commafy a number. That is, insert commas every three number for integers larger than 999. Here is my commafy routine:

sub commafy {
  my $num = shift;
  my $new = "";
  while ($num =~ s/(?<=d)(d{3})$//g) {
    $new = ",$1$new";
  }
  $new = "$num$new";
  return $new;
}

It works backwards from right to the left. It uses the "new" look behind assertion in the regex. Works fine in Perl 5.8, and I think Perl 5.6.

Tags: computers, perl, programming