in reply to Dollars and regex cents

Well, I solution that I'm using now is similar to Dragonchild's suggestion, using simple arithmetic and several assignments to achieve the same effect. The problem with using the printf and sprintf methods is that I'm storing the formatted value into a variable for use later, and not immediately printing it to standard output. O_o

That's why I was hoping for a magical regex to come whisk the kludge from my code. I know it's possible, and it's driving me nuts!

-hig

Replies are listed 'Best First'.
(Ovid) Re(2): Dollars and regex cents
by Ovid (Cardinal) on Sep 06, 2001 at 22:29 UTC

    Not a problem. Just take the routine and put it into a subroutine or method:

    sub convert_to_dollar_format { my $value = shift; $value += 0; # cheap error checking. You'll want something more robust return $value =~ /[^\d.]/ ? 0 : sprintf( '$%.2f', $value ); }

    With that sub, you just call it as you need it and don't worry about using the return value until necessary. Of course, you'll want to customize the error checking to fit your actual needs. Note that sprintf will not print the output (that was a concern you stated), but will merely format it properly).

    As for a regex solution, I wouldn't use one. Regexes are expensive in terms of performance and shouldn't be used if less expensive operations are available.

    Also, the reason you may want to update the error checking is due to it returning zero for non-numeric data. This is similar to Perl's handling of scalars, but probably is going to be harder to debug. I included the "add zero" line so the routine would warn about a non-numeric argument you if you have warnings enabled.

    Cheers,
    Ovid

    Vote for paco!

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: Re: Dollars and regex cents
by wog (Curate) on Sep 06, 2001 at 22:25 UTC
    As documented, sprintf returns a string you do not have to immediately print. You can just take the result of sprintf and store it in a variable.
Re: Re: Dollars and regex cents
by trantor (Chaplain) on Sep 06, 2001 at 22:32 UTC

    higle,
    using s?printf in this context is not a kludge at all! It's simply the most straightforward way to get the job done, we're functions meant for this purpose.

    Without thinking too much about it, I'd guess that a substitution regexp would require the e modifier to get the formatting job done. So it would be more cumbersome, more computationally expensive, harder to debug, probably uglier too :-)

    -- TMTOWTDI