I can create filehandles to strings in Perl 5, how do I do it in Perl 6?

前端 未结 1 1350
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 16:40

In Perl 5, I can create a filehandle to a string and read or write from the string as if it were a file. This is great for working with tests or templates.

For examp

相关标签:
1条回答
  • 2020-12-17 17:08

    Reading

    The idiomatic way to read line-by-line is the .lines method, which is available on both Str and IO::Handle.

    It returns a lazy list which you can pass on to for, as in

    my $text = "A\nB\nC\n";
    
    for $text.lines -> $line {
         # do something with $line
    }
    

    Writing

    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
    

    (Adapted from #perl6, thanks to Carl Mäsak.)

    More advanced cases

    If you need a more sophisticated mechanism to fake file handles, there's IO::Capture::Simple and IO::String in the ecosystem.

    For example:

    use IO::Capture::Simple;
    my $result;
    capture_stdout_on($result);
    say "Howdy there!";
    say "Hai!";
    capture_stdout_off();
    say "Captured string:\n" ~$result;
    
    0 讨论(0)
提交回复
热议问题