When your Perl program starts, it inherits two file handles for output, STDOUT and STDERR. Both go to the console with a bit of a difference, STDOUT is buffered and STDERR is not.
Run time warnings as well as anything that you code as warn "xy"; goes to STDERR. The default print goes to STDOUT.
Many of my scripts just send their output to STDOUT (don't even open a file for output).
To cause the STDERR output to go to the same place, this can be done with the shell, to send the STDOUT and STDERR of something.pl into the more program...
perl something.pl 2>&1 | more
inside something.pl, the statement $|=1; will be important to turn off buffering so that the time sequence of prints to STDOUT and STDERR will be in order.
To cause the STDOUT and STDERR of something.pl to go to the same file: output.txt:
perl something.pl > output.txt 2<&1
To cause STDERR to go to some already opened file handle within a Perl program and also have this "work out right" in terms of output order is something that I hadn't done before and this took some fiddling. Below is my attempt at it and it appears to work. Normally you shouldn't have to do this! But "create a log file for errors and ...data" implies the need for something like this. This is an abnormal situation -- at least it is a first time for me - Normally you want the "real output" to go one place and the "error messages" to go to another place!
#!/usr/bin/perl
use warnings;
use strict;
use IO::Handle;
open (my $fh, '>', 'logfile.txt') || die "can't open logfile.txt";
open (STDERR, ">>&=", $fh) || die "can't redirect STDERR";
$fh->autoflush(1);
my $need_work = 5;
my $i_tried = 0;
while ( $need_work > $i_tried )
{
my $a;
$i_tried++;
print "$a\n"; #this generates a run time warning!!!!!!
warn "this is warning $i_tried"; #an explict warning
print $fh "I've tried $i_tried things as a test\n";
}
__END__
logfile.txt contains:
Use of uninitialized value $a in concatenation (.) or string at C:\TEM
+P\junk2.pl line 18.
this is warning 1 at C:\TEMP\junk2.pl line 19.
I've tried 1 things as a test
Use of uninitialized value $a in concatenation (.) or string at C:\TEM
+P\junk2.pl line 18.
this is warning 2 at C:\TEMP\junk2.pl line 19.
I've tried 2 things as a test
Use of uninitialized value $a in concatenation (.) or string at C:\TEM
+P\junk2.pl line 18.
this is warning 3 at C:\TEMP\junk2.pl line 19.
I've tried 3 things as a test
Use of uninitialized value $a in concatenation (.) or string at C:\TEM
+P\junk2.pl line 18.
this is warning 4 at C:\TEMP\junk2.pl line 19.
I've tried 4 things as a test
Use of uninitialized value $a in concatenation (.) or string at C:\TEM
+P\junk2.pl line 18.
this is warning 5 at C:\TEMP\junk2.pl line 19.
I've tried 5 things as a test
|