closing filehandle for tee STDOUT

A

Andry

Hi all,
I have a problem trying to "tee" STDOUT at some intervals, opening and
closing filehandles.
The following is a sample script:
******************************************************************
#!/usr/bin/perl -w

use File::Tee qw(tee);

$|=1;

open my $target1, '>', 'log1.txt';
tee STDOUT, $target1;
print "line one\n";
close $target1;

open my $target2, '>', 'log2.txt';
tee STDOUT, $target2;
print "line two\n";
close $target2;
*******************************************************************
Given the above script, I expect to write "line one" in log1.txt and
"line two" in log2.txt.
Instead I get both "line one" and "line two" in log1.txt (while
log2.txt only includes "line two").
So I cannot manage to close log1.txt after printing "line one".

Can anyone help with that?

Thank you,
Andrea
 
C

C.DeRykus

Hi all,
I have a problem trying to "tee" STDOUT at some intervals, opening and
closing filehandles.
The following is a sample script:
******************************************************************
#!/usr/bin/perl -w

use File::Tee qw(tee);

$|=1;

open my $target1, '>', 'log1.txt';
tee STDOUT, $target1;
print "line one\n";
close $target1;

open my $target2, '>', 'log2.txt';
tee STDOUT, $target2;
print "line two\n";
close $target2;
*******************************************************************
Given the above script, I expect to write "line one" in log1.txt and
"line two" in log2.txt.
Instead I get both "line one" and "line two" in log1.txt (while
log2.txt only includes "line two").
So I cannot manage to close log1.txt after printing "line one".


I believe you'll need to save/reopen STDOUT:

open my $target1, '>', 'log1.txt' or die $!;
open(my $oldout, ">&STDOUT")
or die "Can't dup STDOUT: $!";

tee STDOUT, $target1;
print "line one\n";
close STDOUT;

open STDOUT, ">&", $oldout or die "Can't dup \$oldout: $!";
open my $target2, '>', 'log2.txt';

tee STDOUT, $target2;
print "line two\n";
close $target2;
 
A

Andry

I believe you'll need to  save/reopen STDOUT:

 open my $target1, '>', 'log1.txt' or die $!;
 open(my $oldout, ">&STDOUT")
      or die "Can't dup STDOUT: $!";

 tee STDOUT, $target1;
 print "line one\n";
 close STDOUT;

 open STDOUT, ">&", $oldout   or die "Can't dup \$oldout: $!";
 open my $target2, '>', 'log2.txt';

 tee STDOUT, $target2;
 print "line two\n";
 close $target2;

Thanks a lot Charles!
That works perfectly.
Thanks to your suggestion I also found a web page showing several
examples for STDOUT manipulation:
http://perldoc.perl.org/functions/open.html

Andrea
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top