string - 将字符串拆分为固定长度的 block 并在 Raku 中写在单独的行中

标签 string raku rakudo

我有一个文件 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/

相关文章:

乐道 Perl 6 : clear screen while using Readline module

performance - 随着 Perl 6 实现的成熟,我们可以期待哪些性能提升?

string - Qt tr国际化不适用于主要功能吗?

python - 如何根据数学符号划分字符串?

raku - Perl 6 是否对将使用的顺序交替做出任何 promise ?

raku - 在Perl 6中是否可以为命名参数提供一个哈希值?

c - 将 null 字符复制到字符串中时,null 仍然会被打印为垃圾

python - 使用 Python 确定字符串是否多次包含相同的单词?

types - 参数化子集

eval - 由于 EVALFILE 引入类符号