String 我可以在Perl 5中创建字符串的文件句柄,在Perl 6中如何创建呢?
在Perl5中,我可以创建一个字符串的文件句柄,并像读取文件一样读取或写入该字符串。这对于使用测试或模板非常有用 例如:String 我可以在Perl 5中创建字符串的文件句柄,在Perl 6中如何创建呢?,string,perl,raku,filehandle,String,Perl,Raku,Filehandle,在Perl5中,我可以创建一个字符串的文件句柄,并像读取文件一样读取或写入该字符串。这对于使用测试或模板非常有用 例如: use v5.10; use strict; use warnings; my $text = "A\nB\nC\n"; open(my $fh, '<', \$text); while(my $line = readline($fh)){ print $line; } use IO::Capture::Simple; my $result; captu
use v5.10; use strict; use warnings;
my $text = "A\nB\nC\n";
open(my $fh, '<', \$text);
while(my $line = readline($fh)){
print $line;
}
use IO::Capture::Simple;
my $result;
capture_stdout_on($result);
say "Howdy there!";
say "Hai!";
capture_stdout_off();
say "Captured string:\n" ~$result;
我收到错误消息:
No such method 'get' for invocant of type 'Str'
in block <unit> at string_fh.p6:8
产出:
My string is 'ABC'
我还没有在Perl 6中看到任何类似的东西。Reading
逐行读取的惯用方法是,在Str
和IO::Handle
上都可以使用
它返回一个惰性列表,您可以将该列表传递给,如中所示
my $text = "A\nB\nC\n";
for $text.lines -> $line {
# do something with $line
}
书写
(改编自Carl Mäsak,多亏了他。)
更严重的病例
如果您需要一种更复杂的机制来伪造文件句柄,那么
例如:
use v5.10; use strict; use warnings;
my $text = "A\nB\nC\n";
open(my $fh, '<', \$text);
while(my $line = readline($fh)){
print $line;
}
use IO::Capture::Simple;
my $result;
capture_stdout_on($result);
say "Howdy there!";
say "Hai!";
capture_stdout_off();
say "Captured string:\n" ~$result;
我喜欢使用显式的
->$foo
位的教学价值,但在实践中,for…
语句对于$text.lines{.foo}通常会更简洁,其中.foo
方法在“it”上被调用。(“It”是变量$\uuu
,当编写类似for
的“主题化程序”时,它会自动赋值)@raiph这是一个偏好问题。我过去经常在Perl 5中使用$\uuuu
,但现在更喜欢显式变量。它可能有点冗长,但我要的是可维护性而不是简洁性。我很高兴Perl 6也是TIMTOWTDI.Btw。while(my$line…{…}
代码在词汇上的作用域与您认为的$line
不同。$行
在词汇上限定了脚本主体周围的上下文。它的范围不限于以下大括号内。相反,使用my
的词法变量声明的作用域是它们的括号。相反,参数的作用域是以下大括号,因为这些大括号是作用于参数的代码块。下面第一个(唯一)答案中的->$line
中的$line
是一个参数。在P5中,$line
是之外的一个未声明变量,而语句(使用strict;使用warnings;
将显示此内容),而在P6中则是已知的。@raiph,好的。现在我看到您的第一条评论完全是指Perl6。我刚刚在Perl 6中尝试了一个while(我的$line=…
循环,你是对的,$line
的作用域在循环之外。但是,它在循环之外没有值。在循环之后,$line.say
打印(任意)
,这意味着它在作用域之内,但基本上没有定义。如果$line.say
打印(Any)
那么这是在while
语句的条件表达式my$line=…
中或在随后的while
语句块中分配给$line
的最后一个“值”(请注意,条件周围的括号是不必要的)。
use IO::Capture::Simple;
my $result;
capture_stdout_on($result);
say "Howdy there!";
say "Hai!";
capture_stdout_off();
say "Captured string:\n" ~$result;