Sometimes I encounter a script or program that wants to
print directly to STDOUT (like Parse::ePerl), but I want it in a scalar variable.
In those cases, I use this StringBuffer module to make a
filehandle that is tied to a scalar.
my $stdout = tie(*STDOUT,'StringBuffer');
print STDOUT 'this will magically get put in $stdout';
open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: $!";
open STDOUT, ">", \$stdout or die $!; # This is where the magic happen
open STDOUT, ">&", $oldout or die $!;
print "Done fooling around\n";
print $stdout; # foo
I've been wishing a perlio layer that allows you to simply open a stream that behaives like any tied handle eg.
# Note: never close one of the three standard handles. It's almost alw
+ays a bad idea.
open OLDSTDOUT, ">&=STDOUT";
open STDOUT, ">:tied(StringBuffer)"; # I presume extra arguments to ti
+e get passed as extra argument to open
print STDOUT "this magically gets put to \$stdout\n";
open STDOUT, ">&=OLDSTDOUT";
print STDOUT "this gets put to the original standard output again\n";