friedman@chekov.UU.NET (Barry Friedman) (03/01/90)
After getting tired of looking at 10 digit+ numbers in a report, I came up with the following routine to insert commas. Unfortunately, I couldn't figure out how to use split to split groups of three so this is kind of long. Hope you find it useful. ex. &commas("9999999"); returns 9,999,999 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = sub commas { local($arg) = $_[0]; local($len) = length($arg); return $arg if($len < 4); local($j, $s, $s1); local($m) = $len % 3; local($i) = $m ? 3 - $m : 0; $arg=substr(" ",0,$i).$arg; $len += $i; undef($s1); for ($j=$len;$j>0; $j=$j-3){ $s=substr($arg,-3,3); $arg=substr($arg,0,$j-3); $s1 = defined($s1) ? $s.",".$s1 : $s; } $s1 =~ s/^ *//; return $s1; } -- Barry Friedman UUCP: ...!uunet!chekov!friedman Emax Computer Systems Inc. 440 Laurier Ave. W., Ottawa, Ont. Canada K1R 5C4
jgreely@giza.cis.ohio-state.edu (J Greely) (03/01/90)
In article <2450@bnr-fos.UUCP> friedman@chekov.UU.NET (Barry Friedman) writes: >After getting tired of looking at 10 digit+ numbers in a report, >I came up with the following routine to insert commas. >Unfortunately, I couldn't figure out how to use split to split groups >of three so this is kind of long. Hope you find it useful. You might like this one, which is a bit shorter, and also handles floating point numbers. It's not bulletproof, but it works. sub commas { local($_,$t1,$t2,$s)=@_; ($_,$s) = /^([0-9]*)(\.[0-9]*)?$/; while () { ($t1,$t2) = /^(.*)(...)$/; last unless $t2; $s = ",$t2$s"; $_ = $t1; } $_ ? $_ . $s : substr($s,1,length($s)); } -- J Greely (jgreely@cis.ohio-state.edu; osu-cis!jgreely)
merlyn@iwarp.intel.com (Randal Schwartz) (03/02/90)
In article <2450@bnr-fos.UUCP>, friedman@chekov (Barry Friedman) writes: | After getting tired of looking at 10 digit+ numbers in a report, | I came up with the following routine to insert commas. | | Unfortunately, I couldn't figure out how to use split to split groups | of three so this is kind of long. Hope you find it useful. | | ex. | &commas("9999999"); returns 9,999,999 [code deleted] How about: sub commas { local($_) = @_; while (s/(.*)(\d)(\d\d\d)/$1$2,$3/) {;} $_; } OK, so I had some practice in Snobol... :-) for('Snobol','Perl'){print"Just another $_ hacker,\n";} -- /=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\ | on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III | | merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn | \=Cute Quote: "Welcome to Portland, Oregon, home of the California Raisins!"=/
tneff@bfmny0.UU.NET (Tom Neff) (03/02/90)
In article <1990Mar1.170610.4475@iwarp.intel.com> merlyn@iwarp.intel.com (Randal Schwartz) writes: > while (s/(.*)(\d)(\d\d\d)/$1$2,$3/) {;} '' while (s/(.*\d)(\d{3})/$1,$2/);