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

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;
}

在Perl 6中,如何像Perl 5一样在字符串上打开文件句柄?其中$message->payloadKafka读取,内容为字节数组。 raiph有一个类似的问题,但它没有回答我的问题。

因此,我想知道如何在Perl 6中打开一个字符串上的文件句柄?这些文档页面没有关于此的信息:


@callyalater,恐怕不行。文档只提到了打开文件,而没有提到在字符串上打开文件句柄。 - chenyf
1
@callyalater,这是一种方便的方法,将包含文件名的字符串转换为对该文件的句柄。我完全理解你认为那是“在字符串上打开一个文件句柄”的原因。但语言是有歧义的,看起来 OP 正在询问一个根本没有涉及到文件的场景,而是假装有一个包含字符串的文件,并打开该虚拟文件。请参阅我刚才链接的SO。 - raiph
@raiph 我现在明白你的意思了。是的,你提供的链接更好。感谢你的澄清。 - callyalater
1
zef安装IO::String - Brad Gilbert
显示剩余2条评论
1个回答

4

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

以下是如何从字符串打开文件句柄,而不是打开不涉及文件的字符串句柄。感谢@raiph澄清了原始问题的含义。


文档中有一个名为输入/输出的部分,描述了这个过程。

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.

这个也可以在Perl5到Perl6页面中找到。

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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接