user2925716
user2925716

Reputation: 999

Writing lines to a binary file

I'm further playing with Raku's CommaIDE and I wanna print a binary file line by line. I've tried this, but it doesn't work:

for "G.txt".IO.lines -> $line {
    say $_;
    }

How shall I fix it ? It's obviously incorrect.

EDIT this doesn't work either, see the snippet bellow

for "G.txt".IO.lines -> $line {
    say $line;
    }

enter image description here

Upvotes: 7

Views: 325

Answers (2)

raydiak
raydiak

Reputation: 61

You're showing us h.raku but Comma is giving you an error regarding c.raku, which is some other file in your Comma project.

It looks like you're working with a text file, not binary. Raku makes a clear distinction here: a text file is treated as text, regardless of encoding. If it's UTF-8, using .lines as you are now should work just fine because that's the default. If it's some other encoding, you can call .lines(:enc<some-other-encoding>). If it's truly binary, then the concept of "lines" really has no meaning, and you want something more like .slurp(:bin), which will give you a Buf[uint8] for working on the byte level.

Upvotes: 6

jubilatious1
jubilatious1

Reputation: 2341

The question specifically refers to reading a binary file, for which reading line-wise may (or may not) make sense--depending on the file.

Here's code to read a binary file straight from the docs (using class IO::CatHandle):

~$ raku -e '(my $f1 = "foo".IO).spurt: "A\nB\nC\n"; (my $f2 = "foo"); with IO::CatHandle.new: $f2 {.encoding: Nil; .slurp.say;};'
    Buf[uint8]:0x<41 0A 42 0A 43 0A>

Compare to reading the file with default encoding (utf8):

~$ raku -e '(my $f1 = "foo".IO).spurt: "A\nB\nC\n"; (my $f2 = "foo"); with IO::CatHandle.new: $f2 {.slurp.say;};'
    A
    B
    C

See: https://docs.raku.org/routine/encoding

Note: the read method uses class IO::Handle which reads binary by default. So the code is simply:

~$ raku -e '(my $file1 = "foo".IO).spurt: "A\nB\nC\n"; my $file2 = "foo".IO; given $file2.open { .read.say; .close;};'
Buf[uint8]:0x<41 0A 42 0A 43 0A>

See: https://docs.raku.org/type/IO::Handle#method_read

For further reading, see discussion of Perl5's <> diamond-operator-equivalent in Raku:
https://docs.raku.org/language/5to6-nutshell#while_until

...and some (older) mailing-list discussion of the same:
https://www.nntp.perl.org/group/perl.perl6.users/2018/11/msg6295.html

Finally, the docs refer to writing a mixed utf8/binary file here (useful for further testing): https://docs.raku.org/routine/encoding#Examples

Upvotes: 5

Related Questions