[Pdx-pm] prefixing, padding, and joining with commas
Eric Wilhelm
enobacon at gmail.com
Fri Jan 13 10:58:19 PST 2012
# from Joshua Keroes
# on Thursday 12 January 2012 17:06:
> 1. I suspect that $c++ line does nothing.
> 2. sprintf or printf will handle that 0-prefixing with less code.
Using sprintf(), map(), and join() eliminates the four instances of
duplicate/pseudo-duplicate "$prefix . $something" code and reduces it
to:
join(', ', map {$prefix . sprintf("%02d", $_)} $start..$last)
Note the concatenation of commas onto $samples, plus the trailing case
with special handling for "add last sample w/o a comma". Using join()
eliminates this special case at the end.
It is also more efficient (for large strings, repeated concatenation can
be very expensive vs growing a list.)
Or, if you would rather read your code from left to right:
use List::oo qw(L);
L($start..$last)->map(sub{$prefix . sprintf("%02d", $_)})->join(', ');
--Eric
--
Issues of control, repair, improvement, cost, or just plain
understandability all come down strongly in favor of open source
solutions to complex problems of any sort.
--Robert G. Brown
---------------------------------------------------
http://scratchcomputing.com
---------------------------------------------------
More information about the Pdx-pm-list
mailing list