Dave's Brain

Browse - programming tips - perl 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.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, 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.
Advertisements: