I wrote:
> [% big_number.chunk(3).join(',') %]
[...]
> Implementation to follow...
'chunk' => sub {
my ($string, $size) = @_;
my @list;
$size ||= 1;
if ($size < 0) {
# sexeger! It's faster to reverse the string, search
# it from the front and then reverse the output than to
# search it from the end, believe it nor not!
$string = reverse $string;
$size = -$size;
unshift(@list, scalar reverse $1)
while ($string =~ /((.{$size})|(.+))/g);
}
else {
push(@list, $1) while ($string =~ /((.{$size})|(.+))/g);
}
return \@list;
},
A positive chunk size chunks it from the left, a negative one from the
right.
Out of interest, note the comment on using a sexeger (reversed regexes)
to perform the chunk-from-right. It does it faster than the regex
to search from the end of the string (regexes are much better
optimised to match at the start of the string).
Here's some timings for the interested.
Benchmark: timing 100000 iterations of left, reverse, right...
left: 6 wallclock secs ( 5.52 usr + 0.02 sys = 5.54 CPU)
reverse: 7 wallclock secs ( 6.34 usr + 0.02 sys = 6.36 CPU)
right: 9 wallclock secs ( 8.77 usr + 0.03 sys = 8.80 CPU)
'left' is the simple left chunk, right is the simple right chunk,
reverse is the optimised reverse right chunk.
> I must admit, for the common case, 'commify' is a lot simpler and
> shorter to type, so maybe we could put that in too?
I accept the points on localisation. Best to have a plugin that
installs the 'commify' plugin for you, based on your locale choices.
A