perlfaq5: "How can I output my numbers with commas added?"
[email protected] ("A. Pagaltzis") Wed, 2 Mar 2005 08:11:03 +0100
| Newsgroups | perl.perlfaq.workers |
|---|---|
| Message-ID | <20050302071103.GA16570@klangraum> |
Hi brian,
you're the perlfaq maintainer these days, right?
I just had to write a commify function and, not thinking about
the way it is usually written, I used unpack and join to do the
job.
Then it occured to me that all snippets I've seen to date, from
the traditional one in the perlfaq to every other variation, use
regex contortions to solve the task -- and few of them are easy
to understand. The traditional perlfaq snippet is in fact one of
the least complicated examples.
Maybe the following could be added to the FAQ, possibly as the
canonical example?
sub commify {
scalar reverse join ',',
unpack '(A3)*',
scalar reverse shift;
}
Case in point, I just wrote this function four times in various
places, without having the exact sequence memorized, and got it
right the first time every time. Not that it's a feat -- but now
just try the same with a regex based commifier...
I know that in times past, the () grouping syntax for unpack()
didn't exist, so back then the regex maybe was the simplest
approach. But we've had this feature for a while now, and I
suggest it might be time to move to a simpler solution as the
canonical one.
Regards,
--
#Aristotle
*AUTOLOAD=*_=sub{s/(.*)::(.*)/print$2,(",$\/"," ")[defined wantarray]/e;$1};
&Just->another->Perl->hacker;