Perl printf to use commas as thousands-separator

The apostrophe format modifier is a non-standard POSIX extension. The documentation for Perl's printf has this to say about such extensions

Perl does its own "sprintf" formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.

The Number::Format module will do this for you, and it takes its default settings from the locale, so is as portable as it can be

use strict;
use warnings 'all';
use v5.10.1;

use Number::Format 'format_number';

say format_number(24500);

output

24,500

A more perl-ish solution:

$a = 12345678;                 # no comment
$b = reverse $a;               # $b = '87654321';
@c = unpack("(A3)*", $b);      # $c = ('876', '543', '21');
$d = join ',', @c;             # $d = '876,543,21';
$e = reverse $d;               # $e = '12,345,678';
print $e;

outputs 12,345,678.

Tags:

Perl