home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomePerl CookbookSearch this book

2.17. Putting Commas in Numbers

Problem

You want to output a number with commas in the right place. People like to see long numbers broken up in this way, especially in reports.

Solution

Reverse the string so you can use backtracking to avoid substitution in the fractional part of the number. Then use a regular expression to find where you need commas, and substitute them in. Finally, reverse the string back.

sub commify {
    my $text = reverse $_[0];
    $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
    return scalar reverse $text;
}

Discussion

It's a lot easier in regular expressions to work from the front than from the back. With this in mind, we reverse the string and make a minor change to the algorithm that repeatedly inserts commas three digits from the end. When all insertions are done, we reverse the final string and return it. Because reverse is sensitive to its implicit return context, we force it to scalar context.

This function can be easily adjusted to accommodate the use of periods instead of commas, as are used in some countries.

Here's an example of commify in action:

# more reasonable web counter :-)
use Math::TrulyRandom;
$hits = truly_random_value();       # negative hits!
$output = "Your web page received $hits accesses last month.\n";
print commify($output);




Your web page received -1,740,525,205 accesses last month.



See Also

perllocale (1); the reverse function in perlfunc (1) and Chapter 3 of Programming Perl ; the section "Adding Commas to a Number" in Chapter 7 of Mastering Regular Expressions


Previous: 2.16. Converting Between Octal and Hexadecimal Perl Cookbook Next: 2.18. Printing Correct Plurals
2.16. Converting Between Octal and Hexadecimal Book Index 2.18. Printing Correct Plurals

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.