我可以在 Perl 5 中为字符串创建文件句柄,我如何在 Perl 6 中做到这一点? [英] I can create filehandles to strings in Perl 5, how do I do it in Perl 6?
问题描述
在 Perl 5 中,我可以创建一个字符串的文件句柄,并从字符串中读取或写入,就像它是一个文件一样.这非常适合处理测试或模板.
In Perl 5, I can create a filehandle to a string and read or write from the string as if it were a file. This is great for working with tests or templates.
例如:
use v5.10; use strict; use warnings;
my $text = "A\nB\nC\n";
open(my $fh, '<', \$text);
while(my $line = readline($fh)){
print $line;
}
我怎样才能在 Perl 6 中做到这一点?以下不适用于 Perl 6(至少不适用于我在 MoarVM 2015.01 来自 2015 年 1 月发布的 Rakudo Star64 位 CentOS 6.5):
How can I do that in Perl 6? The following doesn't work for Perl 6 (at least not for my instance of Perl6 running on MoarVM 2015.01 from the January 2015 release of Rakudo Star on 64-bit CentOS 6.5):
# Warning: This code does not work
use v6;
my $text = "A\nB\nC\n";
my $fh = $text;
while (my $line = $fh.get ) {
$line.say;
}
# Warning: Example of nonfunctional code
我收到错误消息:
No such method 'get' for invocant of type 'Str'
in block <unit> at string_fh.p6:8
Perl5 的 open(my $fh, '<', \$text)
与 Perl6 的 my $fh = $text;
不一样并不奇怪>.所以问题是:如何从 Perl 6 中的字符串创建虚拟文件句柄,如 Perl 5 中的 open(my $fh, '<', \$str)
?或者是尚未实施的内容?
It's not very surprising that Perl5's open(my $fh, '<', \$text)
is not the same as Perl6's my $fh = $text;
. So the question is: How does one create a virtual file handle from a string in Perl 6 like open(my $fh, '<', \$str)
in Perl 5? Or is that something that has yet to be implemented?
更新(在 Perl 5 中写入文件句柄)
UPDATE (writing to a filehandle in Perl 5)
同样,您可以在 Perl 5 中写入字符串文件句柄:
Likewise, you can write to string filehandles in Perl 5:
use v5.10; use strict; use warnings;
my $text = "";
open(my $fh, '>', \$text);
print $fh "A";
print $fh "B";
print $fh "C";
print "My string is '$text'\n";
输出:
My string is 'ABC'
我还没有在 Perl 6 中看到任何类似的东西.
I haven't seen anything remotely similar in Perl 6, yet.
推荐答案
阅读
逐行阅读的惯用方式是 .lines
方法,在 Str
和 IO::Handle
上都可用.
Reading
The idiomatic way to read line-by-line is the .lines
method, which is available on both Str
and IO::Handle
.
它返回一个惰性列表,您可以将其传递给 for
,如
It returns a lazy list which you can pass on to for
, as in
my $text = "A\nB\nC\n";
for $text.lines -> $line {
# do something with $line
}
写作
my $scalar;
my $fh = IO::Handle.new but
role {
method print (*@stuff) { $scalar ~= @stuff };
method print-nl { $scalar ~= "\n" }
};
$fh.say("OH HAI");
$fh.say("bai bai");
say $scalar
# OH HAI
# bai bai
(改编自 #perl6,感谢 Carl Mäsak.)
(Adapted from #perl6, thanks to Carl Mäsak.)
如果您需要更复杂的机制来伪造文件句柄,请使用 IO::Capture::Simple 和 IO::String 在 生态系统.
If you need a more sophisticated mechanism to fake file handles, there's IO::Capture::Simple and IO::String in the ecosystem.
例如:
use IO::Capture::Simple;
my $result;
capture_stdout_on($result);
say "Howdy there!";
say "Hai!";
capture_stdout_off();
say "Captured string:\n" ~$result;
这篇关于我可以在 Perl 5 中为字符串创建文件句柄,我如何在 Perl 6 中做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!