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

时间:2015-02-24 17:54:04

标签: string perl perl6 filehandle 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;
}

我怎样才能在Perl 6中做到这一点?以下 适用于Perl 6(至少不适用于我在MoarVM 2015.01上运行的January 2015 release of Rakudo Star上的Perl6实例-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)?或者是尚未实施的东西?

更新(写入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";

输出:

 My string is 'ABC'

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

1 个答案:

答案 0 :(得分:10)

逐行阅读的惯用方法是.lines methodStrIO::Handle都可以使用。{/ p>

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

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,感谢CarlMäsak。)

更高级的案例

如果您需要更复杂的机制来伪造文件句柄,IO::Capture::Simple中有IO::Stringecosystem

例如:

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