Redirecting STDOUT to Scalar behaves not as expected. Why?

Redirecting STDOUT to Scalar behaves not as expected. Why?

am 27.11.2004 01:24:07 von zaphod

Hi,

to explain what I want to do, I made to demos:

This is the first version, which does exactly what I want to do except,
that it writes STDOUT to a file:

############################################################ ####################
## demo1.pl
############################################################ ####################
use IO::File;

# My Little Programm
my @PROGRAMM = (
"# This is a demo-Programm\n",
"print \"Hello World!\\n\";\n",
"for my \$i (1..5){\n",
" print \"\$i\\n\";\n",
"}\n"
);


# Saving STDOUT
open(OLDOUT,">&STDOUT") || die("[$PROGNAME] Couldn't dup STDOUT\n");


# Redirecting STDOUT to file
close(STDOUT);
die("Couldn't write perl.out\n")
unless open(STDOUT,">perl.out");


# Open Pipe to Perl
my $perl = new IO::File;
$perl->open("|perl");


# Run Programm
for my $code (@PROGRAMM){
print {$perl} $code;
}

# Restore STDOUT
close(STDOUT);
open(STDOUT,">&OLDOUT");

print "Hello again!\n";

############################################################ ####################


now I try to redirect the output to a scalar variable, which works for the
simple print statement, but not for the output of the perl-interpreter
where the programm is piped to:


############################################################ ####################
## demo2.pl
############################################################ ####################
use IO::File;
use IO::Scalar;

# My Little Programm
my @PROGRAMM = (
"# This is a demo-Programm\n",
"print \"Hello World!\\n\";\n",
"for my \$i (1..5){\n",
" print \"\$i\\n\";\n",
"}\n"
);


# Saving STDOUT
open(OLDOUT,">&STDOUT") || die("[$PROGNAME] Couldn't dup STDOUT\n");


# Redirecting STDOUT to Scalar
my $scalar = "";
close(STDOUT);
tie *STDOUT, 'IO::Scalar', \$scalar;

# Show that STDOUT to Scalar works somehow:
print "Hi";

# Open Pipe to Perl
my $perl = new IO::File;
$perl->open("|perl");


# Run Programm
for my $code (@PROGRAMM){
print {$perl} $code;
}



# Restore STDOUT
close(STDOUT);
untie *STDOUT;
open(STDOUT,">&OLDOUT");

print "Hello again!\n";
print ">>>$scalar<<<\n";

############################################################ ####################


What I do not understand is, why there is a different behaviour in the two
versions of the programm and what I can do to capture the result of piping
the programm to perl into $scalar.

Hope there is somebody out there, who can help.


Regards
Thomas

PS.: I know about the existance of "eval", so please no comments about it.