2.16. Putting Commas in Numbers2.16.1. ProblemYou want to output a number with commas in the right places. People like to see long numbers broken up in this way, especially in reports. 2.16.2. SolutionReverse 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; } 2.16.3. DiscussionIt'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 easily be adjusted to accommodate the use of periods instead of commas, as are used in many 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. 2.16.4. See Alsoperllocale(1); the reverse function in perlfunc(1) and Chapter 29 of Programming Perl; the section "Adding Commas to a Number with Lookaround" in Chapter 2 of Mastering Regular Expressions, Second Edition Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|