Perlfunc: Commify

Simple perl function to add commas to a long number to make it more readable.

sub commify {
    # commify a number. Perl Cookbook, 2.17, p. 64
    my $text = reverse $_[0];
    $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
    return scalar reverse $text;
}
Leave A Reply - 3 Replies
Replies
Larry Scott B. 2010-05-19 07:21am - No Email - Logged IP: 144.160.5.25

Here's another (faster) method:

sub commify {
    local $_  = shift;
    1 while s/^(-?\d+)(\d{3})/$1,$2/;
    return $_;
}
Andy 2010-07-30 08:39pm - No Email - Logged IP: 89.134.206.137

That just did n,n,n,n,n,n,n Try this instead:

sub commify {
    local $_ = shift;
    1 while s/^(-?\d+)(\d{3})/$1,$2/;
    return $_;
}
Andy 2010-07-30 08:44pm - No Email - Logged IP: 89.134.206.137

damned filters! Please fix!

Second \d should be followed immediately by leftbrace 3 rightbrace

sub commify {
   local $_ = shift;
   1 while s/^(-?\d+)(\d{3})/$1,$2/;
   return $_;
}
All content licensed under the Creative Commons License