in reply to Re: Numbers with commas
in thread Numbers with commas

From perlfaq5:
How can I output my numbers with commas added? This one will do it for you: sub commify { local $_ = shift; 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; return $_; }

Replies are listed 'Best First'.
Re: Re: Re: Numbers with commas
by tachyon (Chancellor) on May 13, 2004 at 02:10 UTC

    There are a range of variations on the commify theme. That faq version is probably the worst. It is inefficient as it backtracks to do the job and also chokes on things like $1000 or 'string 123456'. The regex in my sub is one of merlyns creations but it chokes on >3 numbers after the decimal point without handling them separately. The Perl cookbook version:

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

    Is more more fault tolerant than the one from the faq.

    cheers

    tachyon

      That faq version is probably the worst.

      Agreed, in general, though there are a range of variations on the "good" theme too.

      The FAQ version is short and doesn't rely on look-ahead. Consequently it is the easiest to copy if you don't care how it works -- and easiest (IMHO) to understand if you do. Short and sweet has significant advantages if you are new to Perl, and that's why it's a good answer to a FAQ.

      I did notice that the cookbook version you quote also appears (more or less) in the FAQ now.