I am calling a function that writes to STDOUT using print. How can I capture this in a variable?
Note that all this happens within the same process.
I am calling a function that writes to STDOUT using print. How can I capture this in a variable?
Note that all this happens within the same process.
The new, cool way to handle this is with Capture::Tiny. You can use it surgically to affect just the part of the program where you need it without disturbing anything else. But, I'd probably do what cjm recommends since that doesn't require a module.
If the code in question is not using STDOUT explicitly (i.e., it just does
print "..."
), you can useselect
to change the filehandle thatprint
uses:Using
select
makes it easier to restore STDOUT afterward. Closing and reopening STDOUT is harder to undo. Note thatselect
does not affect STDOUT itself, so it doesn't affect external processes, but you said you didn't have any. It also doesn't affect code that does something likeprint STDOUT "..."
.If the
select
method isn't sufficient for your needs, I'd recommend you try Capture::Tiny. It can capture output from external programs and code that writes to STDOUT explicitly. But it can't (currently) capture only STDOUT; it always captures both STDOUT and STDERR (either separately or merged into one string).