Search code examples
stringrakurakudo

Split string to fixed length chunks and write in separate line in Raku


I have a file test.txt:

Stringsplittingskills

I want to read this file and write to another file out.txt with three characters in each line like

Str
ing
spl
itt
ing
ski
lls

What I did

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

This runs fine when the length of string is not multiple of 3. When the string length is multiple of 3, it inserts extra newline at the end of output file. How can I avoid inserting new line at the end when the string length is multiple of 3?

I tried another shorter approach,

my $string = "test.txt".IO.slurp;

my $file_handle = "out.txt".IO.open: :w;
for $string.comb(3) -> $line {
    $file_handle.print("$line\n")
}

Still it suffers from same issue.

I looked for here, here but still unable to solve it.


Solution

  • spurt "out.txt", "test.txt".IO.comb(3).join("\n")