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

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

Replies are listed 'Best First'.
Re: Re: Re: Re: Numbers with commas
by TilRMan (Friar) on May 13, 2004 at 06:12 UTC
    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.