1. Perl
  2. Module
  3. here

IO::Capture - Capture standard output/standard error output

Occasionally I have tested standard output. For example, if you want to create interactive programming or test a function that uses print in your source code.

To get the standard output, use the module IO::Capture increase. If you can get the standard output, just perform the automatic test as usual.

IO::Capture is not a standard module, so

cpan IO::Capture

Install with.

1. Capture standard output

To get standard output, use the IO::Capture::Stdout module. It comes with the installation of the IO::Capture module.

The start method starts the capture, and the stop method ends the capture. You can then call the read method to get the captured standard output.

use IO::Capture::Stdout;

my $capture = IO::Capture::Stdout->new;
$capture->start;
print "aaa";
$capture->stop;
my $stdout = $capture->read;

If you want to get the standard output multiple times, you can write as follows.

$capture->start;
print "aaa";
print "bbb";
$capture->stop;
my @stdout = $capture->read;

In the list context, you can get ("aaa", "bbb") by calling read.

How to capture standard output using only standard features

There was also a way to capture standard output using only standard features without using modules, so I'll describe it here.

This is a method to switch the output destination of STDOUT with the open function.

my $stdout;

# Start capturing STDOUT
open my $temp, '> &', STDOUT;
close STDOUT;
open STDOUT, '>', \$stdout;

print "hoge";

# STDOUT capture finished
close STDOUT;
open STDOUT, '> &', $temp;
close $temp;

print $stdout; # "hoge" is output

2. Capture standard error output

You can do the same with IO::Capture::Stderr.

use IO::Capture::Stderr;

my $capture = IO::Capture::Stderr->new;
$capture->start;
print STDERR "aaa";
$capture->stop;
my $stderr = $capture->read;

How to capture standard error using only standard features

There was also a way to capture standard error output using only standard features without using modules, so I will describe it here.

This is a method to switch the output destination of STDERR with the open function.

my $stderr;

# Start capture STDERR
open my $temp, '> &', STDERR;
close STDERR;
open STDERR, '>', \$stderr;

print STDERR "hoge";

# End capture STDERR
close STDERR;
open STDERR, '> &', $temp;
close $temp;


print $stderr; # "hoge" is output

Related Informatrion