我可以在Perl 5中为字符串创建文件句柄,我该如何在Perl 6中完成?

Chr*_*oms 13 string perl filehandle perl6 raku

在Perl 5中,我可以创建一个字符串的文件句柄,并从字符串中读取或写入,就好像它是一个文件一样.这非常适合使用测试或模板.

例如:

use v5.10; use strict; use warnings;

my $text = "A\nB\nC\n";

open(my $fh, '<', \$text);

while(my $line = readline($fh)){
    print $line;
}
Run Code Online (Sandbox Code Playgroud)

我怎么能在Perl 6中做到这一点?以下为Perl 6的工作(至少对于上运行我的Perl6的实例MoarVM 2015.01Rakudo星2015年1月发布 64位的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
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

No such method 'get' for invocant of type 'Str'
   in block <unit> at string_fh.p6:8
Run Code Online (Sandbox Code Playgroud)

Perl5 open(my $fh, '<', \$text)与Perl6不同,这并不奇怪my $fh = $text;.所以问题是:如何从Perl 6中的字符串创建虚拟文件句柄,就像open(my $fh, '<', \$str)在Perl 5中一样?还是那个尚未实施的东西?

更新(写入Perl 5中的文件句柄)

同样,您可以在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";
Run Code Online (Sandbox Code Playgroud)

输出:

 My string is 'ABC'
Run Code Online (Sandbox Code Playgroud)

我还没有在Perl 6中看到过类似的东西.

Chr*_*oph 10

读取线由行惯用的方法是.lines方法,其可在两个StrIO::Handle.

它返回一个惰性列表,您可以传递给它for,如

my $text = "A\nB\nC\n";

for $text.lines -> $line {
     # do something with $line
}
Run Code Online (Sandbox Code Playgroud)

写作

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
Run Code Online (Sandbox Code Playgroud)

(改编自#perl6,感谢CarlMäsak.)

更高级的案例

如果你需要一个更复杂的机制,以假文件句柄,有IO ::捕捉::简单IO ::字符串生态系统.

例如:

use IO::Capture::Simple;
my $result;
capture_stdout_on($result);
say "Howdy there!";
say "Hai!";
capture_stdout_off();
say "Captured string:\n" ~$result;
Run Code Online (Sandbox Code Playgroud)