質問

I'm trying to write some unit tests for some communications code that writes to a socket. During testing I'd like to have my communications library write to a string, then I can compare the contents of the string to what I expect to be written.

In Java I'd use something like a StringWriter so that my communications code could write to the standard Writer interface and at the end I can just ask for all of the data that was written.

Is there an equivalent of this or Python's StringIO for Perl? Is something like this already built in?

役に立ちましたか?

解決

Yes. Since v5.8 you can open an output handle directly to a scalar reference.

my $output;
open my $handle, '>', \$output;
print $handle "foo\n";
printf $handle "%d\n", 123;
close $handle;
print $output;   # => "foo\n123\n"

他のヒント

You can do similar things with IO::Stringy.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top