[LUNI] Changing an expression in perl...
Joe Digilio
joedigilio at yahoo.com
Tue Aug 13 08:34:01 CDT 2002
Or if you don't want to use a module, a quick search with perldoc turns
up this in perlfaq5:
Found in /usr/share/perl/5.6.1/pod/perlfaq5.pod
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 $_;
}
$n = 23659019423.2331;
print "GOT: ", commify($n), "\n";
GOT: 23,659,019,423.2331
You can't just:
s/^([-+]?\d+)(\d{3})/$1,$2/g;
because you have to put the comma in and then recalculate your
position.
Alternatively, this code commifies all numbers in a line
regardless of
whether they have decimal portions, are preceded by + or -, or
whatever:
# from Andrew Johnson <ajohnson at gpu.srv.ualberta.ca>
sub commify {
my $input = shift;
$input = reverse $input;
$input =~ s<(\d\d\d)(?=\d)(?!\d*\.)><$1,>g;
return scalar reverse $input;
}
--- "Keith T. Garner" <kgarner at kgarner.com> wrote:
> On Mon, Aug 12, 2002 at 11:11:08, Joel F. Hacker said:
> > Sorry that this is a little off topic,
> > but does anyone know how to change scalar
> > operators like 2345.23 into a string
> > like 2,345.23
> >
> > or
> >
> > 2325364.32 to 2,325,364.32
>
> A quick search of CPAN shows that you probably want to use the
> Number::Format module. It looks like it already has a method to do
> what you want....
>
> $formatted = format_price($number, $precision);
>
> http://search.cpan.org/author/WRW/Number-Format-1.44/Format.pm
>
> Keith
>
> --
> Keith T. Garner
> kgarner at kgarner.com
> The whole problem with the world is that fools and fanatics are
> always so
> certain of themselves, and wiser people so full of doubts.
> --Bertrand Russell
>
______________________________________________________________________
> Linux Users Of Northern Illinois - Technical Discussion
> luni at luni.org
> http://luni.org/mailman/listinfo/luni
__________________________________________________
Do You Yahoo!?
HotJobs - Search Thousands of New Jobs
http://www.hotjobs.com
More information about the luni
mailing list