Perl: printing on a "display" as well as a file

Is there a way to print both on the "display" and in the file at the same time without repeating the "string" print code?

What I want to do:

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

instead:

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

I tried googling search, but all I found was either or not two functions together.

Edit to add questions:

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

@EricStrom What do you understand when creating a new tee'd pen? 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 an alternative inside the default library?

+4
source share
4 answers

Of course, with IO :: Tee in CPAN.

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

To change the default perl descriptor:

 select $tee; print "HELLO!\n"; 
+9
source

If this is for logging, consider using Log :: Log4perl

You can have the same material journal on a screen, file, or even a database.

This is a complete example of logging both on screen and on file.

 use strict; use Log::Log4perl qw(:easy); Log::Log4perl->easy_init("INFO"); my $logConfiguration = qq( log4perl.logger = INFO, Logfile, Screen log4perl.appender.Logfile = Log::Log4perl::Appender::File log4perl.appender.Logfile.filename = C:\\temp\\file.log log4perl.appender.Logfile.layout = Log::Log4perl::Layout::PatternLayout log4perl.appender.Logfile.layout.ConversionPattern =%p[%d{MM/dd HH:mm} %3L] %m%n log4perl.appender.Screen = Log::Log4perl::Appender::Screen log4perl.appender.Screen.stderr = 0 log4perl.appender.Screen.layout = Log::Log4perl::Layout::SimpleLayout log4perl.appender.Screen.layout.ConversionPattern = %m%n ); Log::Log4perl::init( \$logConfiguration ); INFO "This line will be logged"; ERROR "This error will be logged"; LOGDIE "Fatal error will be logged"; 

The configuration shows that when creating INFO , ERROR , etc. both the file ( Logfile ) and the screen ( Screen ) will be added.

FAQ contains more questions

+5
source

Why not make a routine for the task?

In addition, many logging packages such as Log :: Log4perl support writing to both the console and the file through a fairly simple configuration.

+1
source

Source: https://habr.com/ru/post/1387789/


All Articles