我有一个文件 test.txt
:
Stringsplittingskills
我想读取这个文件并写入另一个文件
out.txt
每行三个字符,如Str
ing
spl
itt
ing
ski
lls
我做了什么
my $string = "test.txt".IO.slurp;
my $start = 0;
my $elements = $string.chars;
# open file in writing mode
my $file_handle = "out.txt".IO.open: :w;
while $start < $elements {
my $line = $string.substr($start,3);
if $line.chars == 3 {
$file_handle.print("$line\n")
} elsif $line.chars < 3 {
$file_handle.print("$line")
}
$start = $start + 3;
}
# close file handle
$file_handle.close
当字符串的长度不是 3 的倍数时,这运行良好。当字符串长度是 3 的倍数时,它会在输出文件的末尾插入额外的换行符。当字符串长度是 3 的倍数时,如何避免在末尾插入新行?
我尝试了另一种更短的方法,
my $string = "test.txt".IO.slurp;
my $file_handle = "out.txt".IO.open: :w;
for $string.comb(3) -> $line {
$file_handle.print("$line\n")
}
它仍然遭受同样的问题。
我找了 here , here但仍然无法解决。
最佳答案
spurt "out.txt", "test.txt".IO.comb(3).join("\n")
关于string - 将字符串拆分为固定长度的 block 并在 Raku 中写在单独的行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61875715/