The unpack method is probably the most efficient, if a bit obtuse. The regex method is probably the most Perlish way to do it. But since this is Perl, there is more than one way to do it, so here are a few other fun ways you could do this:
using List::MoreUtils::natatime
("n-at-a-time"). This method is of course wildly wasteful of memory, creating a scalar for every 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 "replacement" argument of substr
to splice in newlines, working from the end: (you have to work from the end because otherwise further offsets no longer line up after you start adding newlines; also working from the end means you only calculate length $in
at loop start time 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 could pre-calculate all the offsets and extract them using substr
foreach (map $_ * 5, 0 .. int(length($in) / 5)) {
$out .= substr($in, $_, 5) . "\n";
}
probably the most succinct way using substr
is to use replacement and concatenate the return value:
$out .= substr($in, 0, 5, '') . "\n" while $in;