frankus has asked for the wisdom of the Perl Monks concerning the following question:

Earlier today on the chatterbox someone asked how to seperate a number with numbers after each set of three digits.

i.e. 123456789 = 123,456,789

I really thought this was a cool use for Regular Expressions. The problem as I saw it required the regular expression to work on the result. I came up with this:

for(;;){s/^(\d+)(\d{3}($|,))(.*)/$1,$2,$4/;$2||last}
It seems to lack some of the grace I have come to expect from regular expressions. Anyone got an idea.

--
Brother Frankus.

Replies are listed 'Best First'.
Re: Regular question
by Fastolfe (Vicar) on Nov 09, 2000 at 23:24 UTC
RE: Regular question
by Blue (Hermit) on Nov 09, 2000 at 23:34 UTC
    Perhaps the best way would be to reverse the number and then add in commas every three, and reverse back, such as:

    #!/usr/bin/perl -w use strict; sub commafy { my ($num)=@_; $num=reverse $num; $num=~s/(\d{3})(?=\d)/$1,/g; $num=reverse $num; } my $example = commafy(123456789); print "$example\n";
    Picked up that little trick here, and it's rather useful.

    =Blue
    ...you might be eaten by a grue...

    UPDATE: The links Fastolfe gave lead to more complete answers then mine, which only deals with integers.

Regular question errata.
by frankus (Priest) on Nov 09, 2000 at 23:16 UTC
    D'oh, it should be seperating a number with comments. And the exact question is: is there a regular expression suffix that makes the regex reprocess it's results?

    Apologies to all readers, it's late, my brain hurt, I go now.

    --
    
    Brother Frankus.