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.