|laziness, impatience, and hubris|
Printing large numbers with commas to show thousands groups.by jnorden (Novice)
|on Dec 27, 2019 at 01:13 UTC||Need Help??|
Here is yet another answer to this ancient and oft-asked question (for linux at least).
The standard advice is found in perlfaq5, on perlmonks, and elsewhere. Using Number::Format or a commify() sub works well, but isn't very convenient for modifying existing code that was written with printf. It seems unlikely that perl's printf will ever support %'d and friends (see printf(3), scroll to "Flag Characters").
However, almost any linux system has a /usr/bin/printf command with %' support. So, the simple definition
will let you use
to print: There are at least 42,000,000 ways to do it!
For this to work, your LC_NUMERIC environment variable should be set to a locale that has a "thousands separator", such as en_US.UTF-8. It seems to work quite well, at least for simple cases. To modify existing code, just change your printf's to cprintf's and add apostrophe's to the formats as needed. Less work than wrapping each argument with a subroutine call and changing each format to %s. It also helps keep things clear and readable.
It's tempting to override the builtin printf, but that's not easy to do. The CORE documentation lists printf as a special keyword. (Playing with tied file-handles or other tricks might work, but doesn't seem worth it too me.)
On the other hand, if you want to auto-magically commify *all* your %d's, you could use:
And then cprintf("%d", 42e6) will print 42,000,000.
Of course, there are plenty of potential pitfalls to this simple approach, including:
This works because perl puts two strings into **argv and then directly execs /usr/bin/printf. But,
will do something quite different, since perl will pass the single string to a shell, which will then execute ls. Replace 'ls' with 'rm' (or, horrors, 'rm -rf') and you've got a disaster on your hands!
Happy Holidays, and best wishes for the new year!