unpack 方法可能是最有效的,虽然有点迟钝。正则表达式方法可能是最 Perlish 的方法。但由于这是 Perl,有不止一种方法可以做到这一点,所以这里有一些其他有趣的方法可以做到这一点:
使用List::MoreUtils::natatime ("n-at-a-time")。这种方法当然会非常浪费内存,为字符串中的每个字符创建一个标量。
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";
}
使用substr 的“替换”参数拼接换行符,从头开始工作:(您必须从头开始工作,否则在开始添加换行符后进一步的偏移量不再排列;也从头开始工作意味着您只在循环开始时计算length $in,而不使用额外的变量)
for(my $i = length($in) - length($in) % 5; $i; $i -= 5) {
substr($in, $i, 0, "\n");
}
如果您想保持输入变量不变,您可以预先计算所有偏移量并使用substr提取它们
foreach (map $_ * 5, 0 .. int(length($in) / 5)) {
$out .= substr($in, $_, 5) . "\n";
}
使用substr 的最简洁的方法可能是使用替换并连接返回值:
$out .= substr($in, 0, 5, '') . "\n" while $in;