perlqx

How can I change the standard output filehandle for a system call in Perl?


I am trying change the stdout of the system function using select. But it does not seem to be working. The system output is getting displayed on console rather than getting redirected to the file.

use strict;
use warnings;

chdir "C:\\Documents and Settings\\" or die "cannot open the dir\n";
open FH, ">out.txt" or die "cannot open out.txt\n";
select FH or die " cannot change the stdout\n";
system "dir /a" ; 

Although I can do system "dir /a > out.txt", I want to know why the above code is not working.


Solution

  • The select function changes the default filehandle for output. It does not change STDOUT, which points to whatever it points to regardless if it is the default filehandle for output. If you want to change STDOUT, you have to do something like ylebre or Jon's answer.

    When you start a child process, it gets the same standard output as the parent. It doesn't care what the default filehandle of the parent is though.