在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工作(至少不是我运行的Perl6实例) MoarVM 2015.01 来自 2015年1月Rakudo Star发布 在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
我收到错误消息:
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中的字符串创建虚拟文件句柄 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";
输出:
My string is 'ABC'
我还没有在Perl 6中看到过类似的东西。