在 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上运行的 Perl6 实例,从2015 年 1 月发布的64 位 CentOS 6.5 上的 Rakudo Star开始):
# 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
open(my $fh, '<', \$text)
Perl5与 Perl6 不同,这并不奇怪my $fh = $text;
。所以问题是:如何像open(my $fh, '<', \$str)
在 Perl 5 中一样从 Perl 6 中的字符串创建虚拟文件句柄?或者这是尚未实施的事情?
更新(在 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 中看到任何类似的东西。