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. |