سؤال

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