chidori
chidori

Reputation: 1112

unable to generate error and redirect it to a file in perl

I am trying to redirect my STDOUT and STDERR to some file. I am successful with that to some extent. But i am not able to understand one thing in the below code.

#!/usr/bin/perl
open (STDOUT,">/var/tmp/outfile") or die "problem : $!";
open (STDERR,">>/var/tmp/outfile") or die "problem : $!";
print "$_\n" foreach (1..10);
sdsdf;  # buggy line inserted wantedly

I have inserted the last line assuming that perl would throwout an error and that would be redirected to the file but its not happening . My program does not throughout any error onto the screen nor to the outfile. Please help me understand this behavior.

Upvotes: 0

Views: 249

Answers (2)

ikegami
ikegami

Reputation: 385546

Without use strict;,

 sdsdf;

is the same as

 "sdsdf";

That's one of the reasons you always want to use use strict; use warnings;. Let's start by adding that.


So you want to log all output including compile-time errors to a file. Well, that's not going to happen by redirecting STDERR after your code has been compiled. The best way to do this is from outside your program.

script.pl >/var/tmp/outfile 2>&1

but it can be done from within your program.

#!/usr/bin/perl
use strict;
use warnings;

BEGIN {
   open(STDOUT, '>', '/var/tmp/outfile')
      or die("Can't redirect STDOUT: $!\n");
   open(STDERR, '>&', \*STDOUT)
      or die("Can't redirect STDERR: $!\n");
}

print "$_\n" foreach (1..10);
sdsdf;  # Syntax error

Upvotes: 1

perreal
perreal

Reputation: 97918

The sdsdf is not generating any errors (if you use strict then you'll see some compile time errors), that's why you are not seeing any messages. Try this:

use warnings;
use strict;
open (STDOUT,">outfile1") or die "problem : $!";
open STDERR, ">&STDOUT";
print "$_\n" foreach (1..10);
die("aaaa");  # buggy line inserted wantedly

Also in your code you are opening the same file twice, this might cause some problems. In the above we first redirect the stdout to a file then redirect stderr to stdout.

Upvotes: 3

Related Questions