Dave's Brain

Browse - Programming Tips - How do I redirect/capture STDOUT to a $variable ?

Date: 2010jun28
Language: perl

Q.   How do I redirect/capture STDOUT to a $variable ?

A.  There are various ways.  But I like this the best.
Make a subroutine that declares *STDOUT has a local like this:

sub capture_stdout() { my($v); local *STDOUT; open(STDOUT, '>', \$v); print "one\n"; do_something_that_outputs_to_stdout(); print "two\n"; return $v; }
The scope of the local is the inside of the brace brackets so there is no need to close, etc.

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.