3

In Perl 6 the Str type is immutable, so it seems reasonable to use a mutable buffer instead of concatenating a lot of strings. Next, I like being able to use the same API regardless if my function is writing to stdout, file or to an in-memory buffer.

In Perl, I can create an in-memory file like so

my $var = "";
open my $fh, '>', \$var;
print $fh "asdf";
close $fh;
print $var;          # asdf

How do I achieve the same thing in Perl 6?

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
user7610
  • 25,267
  • 15
  • 124
  • 150
  • 2
    cf https://stackoverflow.com/questions/28702850/i-can-create-filehandles-to-strings-in-perl-5-how-do-i-do-it-in-perl-6 – Christoph Oct 26 '15 at 20:24

2 Answers2

3

There's a minimal IO::String in the ecosystem backed by an array.

For a one-off solution, you could also do someting like

my $string;
my $handle = IO::Handle.new but role {
    method print(*@stuff) { $string ~= @stuff.join };
    method print-nl       { $string ~= "\n" }
};

$handle.say("The answer you're looking for is 42.");
dd $string;
Christoph
  • 164,997
  • 36
  • 182
  • 240
2

What I currently do is that I wrapped string concatenation in a class as a temporary solution.

class Buffer {
    has $!buf = "";
    multi method print($string) {
        $!buf ~= $string;
    }
    multi method say($string) {
        $!buf ~= $string ~ "\n";
    }
    multi method Str() {
        return $!buf;
    }
}

With that, I can do

my $buf = Buffer.new();
say $buf: "asdf";
print $buf.Str;
user7610
  • 25,267
  • 15
  • 124
  • 150