Dirk Bremer wrote:
> I am looking for a regex to be used for comma substitution for numbers,
i.e. the regex would transform:
>
> 999 = 999
> 9999 = 9,999
> 99999 = 99,999
> 999999 = 999,999
> 9999999 = 9,999,999, etc.
>
> I tried s/(\d{3})/,$1/g, but for certain numbers it leaves a leading
comma, i.e. 999999 = ,999,999. Please advise.
I don't remember where I got this, but here's a short solution:
****************** contents of t.pl ******************
#!/usr/bin/perl
#tested
sub commify($); # puts a comma every 3 numeric characters in a submitted string
for (@ARGV) { my $val = commify($_); print "$val\n" }
sub commify($) {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}
****************** end of t.pl ******************
Here are the results of a series of tests. As you can see,
this handles positive and negative numbers, with or without
decimal portions.
Have fun!
--- John
C:\>perl t.pl 1 12 123 1234 12345 123456 1234567
1
12
123
1,234
12,345
123,456
1,234,567
C:\>perl t.pl -1 -12 -123 -1234 -12345 -123456 -1234567
-1
-12
-123
-1,234
-12,345
-123,456
-1,234,567
C:\>perl t.pl 1.12345 12.12345 123.12345 1234.12345 12345.12345
123456.12345 1234567.12345
1.12345
12.12345
123.12345
1,234.12345
12,345.12345
123,456.12345
1,234,567.12345
C:\>perl t.pl -1.12345 -12.12345 -123.12345 -1234.12345 -12345.12345
-123456.12345 -1234567.12345
-1.12345
-12.12345
-123.12345
-1,234.12345
-12,345.12345
-123,456.12345
-1,234,567.12345
C:\>perl t.pl +1.12345 +12.12345 +123.12345 +1234.12345 +12345.12345
+123456.12345 +1234567.12345
+1.12345
+12.12345
+123.12345
+1,234.12345
+12,345.12345
+123,456.12345
+1,234,567.12345
This is my version of Perl:
This is perl, v5.6.1 built for MSWin32-x86-multi-thread
(with 1 registered patch, see perl -V for more detail)
Copyright 1987-2001, Larry Wall
Binary build 630 provided by ActiveState Tool Corp. http://www.ActiveState.com
Built 20:29:41 Oct 31 2001
_______________________________________________
Perl-Win32-Users mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/perl-win32-users