TITLE
IO::String
SYNOPSIS
use IO::String;
# Using IO to write a Str
my $buffer = IO::String.new;
{
my $*OUT = $buffer;
say "hello";
}
say ~$buffer; # T<hello>
# Using IO to read a Str
my $sh = IO::String.new(:$buffer)
for $sh.lines -> $line {
say $line; # T<hello>
}
DESCRIPTION
Sometimes you want to use code that deals with files (or other
file-like objects), but you don't want to mess around with creating
temporary files. This includes uses like APIs that for some reason
don't accept strings as well as files as targets, mocking I/O,
or capturing output written to the terminal. That's why this module
exists. Loosely based on Perl 5's IO::String.
TODO
Handle encodings
METHODS
method new
method new(
Str :$buffer = '',
Str :$pos = 0,
Str :$chomp = True,
Str :$nl-in = ["\x0a", "\r\n"],
Str:D :$nl-out = "\n",
) returns IO::String:D
This creates a new IO::String handle. Every IO::String is also a IO::Handle and can be used in place of a file handle. The $buffer
is the string to read from or write to. The $pos
is the current position to start the next read or write.
The $chomp
, $nl-in
, and $nl-out
options are from of IO::Handle. When reading line-by-line, $chomp
the chomp setting is used to determine whether the line endings should be chomped or left in place. The $nl-in
is an array of strings that will be used to end line records during reads and $nl-out
is the string that will be appended for new lines at the end of any output line record.
method open
multi method open(
Str $buffer is rw,
Bool :$bind,
);
multi method open(Str $buffer)
This tells the IO::String object to start working with a new string. Passing a variable and setting the :bind
option will result in that value being bound to the IO::String object. Any write to the handle will result in a change to the original string. For example,
my $s;
my $h = IO::String.new;
$h.open($s, :bind);
$h.say("hello");
say $s; # hello <-- the original string changed
With :bind
set to false or without being passed, the string will not be bound and changes to the handle will not change the original.