如何在 Perl 6 中打开字符串上的文件句柄?

How to open a file handle on a string in Perl 6?

在 Perl 5 中,我可以像这样打开字符串上的文件句柄:

open my $kfh, "<", $message->payload;

我有一个使用字符串作为文件句柄并将其传递给 open 方法的场景:

my $fh = new IO::Zlib;
open my $kfh, "<", $message->payload;
if($fh->open($kfh, 'rb')){
   print <$fh>;
   $fh->close;
}

其中 $message->payload 是从 Kafka, and the content is a byte array. raiph had a 读取的,但它没有回答我的问题。

所以我想知道如何像 Perl 5 一样在 Perl 6 中打开字符串上的文件句柄?这些文档页面没有这方面的信息:

编辑:请参阅 以了解如何执行 @raiph 所说的打开字符串文件句柄的操作。另外,阅读@raiph 的评论。

这是如何从字符串打开 文件 的文件句柄,而不是如何在没有字符串的情况下打开 字符串 的文件句柄涉及的文件。感谢@raiph 阐明了 OP 的含义。


文档中有一个名为 Input/Output 的部分描述了此过程。

One way to read the contents of a file is to open the file via the open function with the :r (read) file mode option and slurp in the contents:

my $fh = open "testfile", :r;
my $contents = $fh.slurp-rest;
$fh.close;

Here we explicitly close the filehandle using the close method on the IO::Handle object. This is a very traditional way of reading the contents of a file. However, the same can be done more easily and clearly like so:

my $contents = "testfile".IO.slurp;
# or in procedural form: 
$contents = slurp "testfile"

By adding the IO role to the file name string, we are effectively able to refer to the string as the file object itself and thus slurp in its contents directly. Note that the slurp takes care of opening and closing the file for you.

This is also found in the Perl5 to Perl6 pages as well.

In Perl 5, a common idiom for reading the lines of a text file goes something like this:

open my $fh, "<", "file" or die "$!";
my @lines = <$fh>;                # lines are NOT chomped 
close $fh;`

In Perl 6, this has been simplified to

my @lines = "file".IO.lines; # auto-chomped

IO::Handle 文档中可以找到有关执行此操作的更多参考资料:

Instances of IO::Handle encapsulate an handle to manipulate input/output resources. Usually there is no need to create directly an IO::Handle instance, since it will be done by other roles and methods. For instance, an IO::Path object provides an open method that returns an IO::Handle:

my $fh = '/tmp/log.txt'.IO.open;
say $fh.^name; # OUTPUT: IO::Handle