ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
2.17. Putting Commas in NumbersProblemYou 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. 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; } 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 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 # 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);
See Alsoperllocale (1); the |