문제

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