|
Posted by Mario D'Alessio on June 10, 2008, 11:15 am
Please log in for more thread options
Rather than using a complex RE, I reverse the
string and then just add a comma after each set
of 3 numbers:
$s = reverse $s;
$s =~ s/(\d)/,/g;
$s =~ s/,$//;
reverse $s;
Besides the fact that my code ignores the plus
and minus signs and the decimal point, is there any
other advantage to using the REs below? I'm guessing
that my two uses of "reverse" and the simple RE would
be more efficient than the complex REs below.
Just wondering...
Mario
> This is an excerpt from the latest version perlfaq5.pod, which
> comes with the standard Perl distribution. These postings aim to
> reduce the number of repeated questions as well as allow the community
> to review and update the answers. The latest version of the complete
> perlfaq is at http://faq.perl.org .
>
> --------------------------------------------------------------------
>
> 5.13: How can I output my numbers with commas added?
>
>
> (contributed by brian d foy and Benjamin Goldberg)
>
> You can use Number::Format to separate places in a number. It handles
> locale information for those of you who want to insert full stops
> instead (or anything else that they want to use, really).
>
> This subroutine will add commas to your number:
>
> sub commify {
> local $_ = shift;
> 1 while s/^([-+]?\d+)(\d)/$1,$2/;
> return $_;
> }
>
> This regex from Benjamin Goldberg will add commas to numbers:
>
> s/(^[-+]?\d+?(?=(?>(?:\d)+)(?!\d))|\G\d(?=\d))/$1,/g;
>
> It is easier to see with comments:
>
> s/(
> ^[-+]? # beginning of number.
> \d+? # first digits before first comma
> (?= # followed by, (but not included in
> the match) :
> (?>(?:\d)+) # some positive multiple of
> three digits.
> (?!\d) # an *exact* multiple, not x * 3
> + 1 or whatever.
> )
> | # or:
> \G\d # after the last group, get three
> digits
> (?=\d) # but they have to have more digits
> after them.
> )/$1,/xg;
>
>
>
> --------------------------------------------------------------------
>
> The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
> are not necessarily experts in every domain where Perl might show up,
> so please include as much information as possible and relevant in any
> corrections. The perlfaq-workers also don't have access to every
> operating system or platform, so please include relevant details for
> corrections to examples that do not work on particular platforms.
> Working code is greatly appreciated.
>
> If you'd like to help maintain the perlfaq, see the details in
> perlfaq.pod.
|