in reply to Making money look nice
This outputswhile (<DATA>) { chomp; print commify($_), "\n"; } # From _The Perl Cookbook_, recipe 2.17 sub commify { my $text = reverse $_[0]; $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g; return scalar reverse $text; } __DATA__ 195000 42000 2100
Here's the discussion in the book:195,000 42,000 2,100
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Making money look nice
by TGI (Parson) on Apr 12, 2003 at 00:34 UTC |