Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

string - Perl: Print on the "display" and also into a file

Is there any way to print both onto the "display" and also into a file at the same time without repeating the print "string" code?

What I want to do:

if ($ofile) {
   open (FILE, '>>', "file");
   print "Hello" #some code#; #prints on the display and into the file
}

instead of:

if ($ofile) { open (FILE, '>>', "file"); }
print "Hello";
if ($ofile) { print FILE "Hello"; }

Tried googling but all I found was either or, not both features together.

Edit to add questions:

Then use IO::Tee to create a new tee'd handle, and then select $tee so that print uses it by default. – Eric Strom

@EricStrom What do you mean by create a new tee'd handle? Do you mean this Local::TeeOutput? search.cpan.org/~mschilli/Log-Log4perl-1.34/lib/Log/Log4perl.pm

@EricStrom Do you have an example?

@EricStrom Local::TeeOutput is not available in the default library for Strawberry Perl. Is there any alternative that's inside the default library?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, with IO::Tee on CPAN.

my $tee = IO::Tee->new( *STDOUT, *STDERR, $John, $Tan );
print $tee "HELLO!
";

To change perl's default handle:

select $tee;
print "HELLO!
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...