Sum*_*nal 5 string rakudo raku
我有一个文件test.txt:
Stringsplittingskills
Run Code Online (Sandbox Code Playgroud)
我想读取这个文件并写入另一个文件out.txt,每行三个字符,如
Str
ing
spl
itt
ing
ski
lls
Run Code Online (Sandbox Code Playgroud)
我做了什么
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
Run Code Online (Sandbox Code Playgroud)
当字符串的长度不是 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")
}
Run Code Online (Sandbox Code Playgroud)
它仍然遭受同样的问题。
spurt "out.txt", "test.txt".IO.comb(3).join("\n")
Run Code Online (Sandbox Code Playgroud)