The unpacking method is probably the most effective if a little dumb. The regex method is probably the most Perlish way to do this. But since this is Perl, there is more than one way to do this, so there are a few more interesting ways to do this:
using List::MoreUtils::natatime ("n-at-a-time"). This method, of course, wildly wasteful memory, creating a scalar for each character in the string.
use List::MoreUtils qw(natatime); my $in = "aaaaabbbbbcccccdd"; my $out = ''; my $it = natatime 5, split //, $in; while(my @chars = $it->()) { $out .= $_ for @chars; $out .= "\n"; }
using the substr argument substr for splicing in new lines, working from the end: (you must work from the end, because otherwise further offsets no longer line up after you start adding new lines, and also work from the end means what do you calculate length $in at the start of the loop without using an extra variable)
for(my $i = length($in) - length($in) % 5; $i; $i -= 5) { substr($in, $i, 0, "\n"); }
if you want to keep the input variable as is, you can pre-calculate all offsets and extract them with substr
foreach (map $_ * 5, 0 .. int(length($in) / 5)) { $out .= substr($in, $_, 5) . "\n"; }
perhaps the most concise way to use substr is to use substitution and concatenate the return value:
$out .= substr($in, 0, 5, '') . "\n" while $in;
nohat
source share