views:

426

answers:

5

I'm looking for an example of redirecting stdout to a file using Perl. I'm doing a fairly straightforward fork/exec tool, and I want to redirect the child's output to a file instead of the parents stdout.

Is there an equivilant of dup2() I should use? I can't seem to find it

+11  A: 

From perldoc -f open:

open STDOUT, '>', "foo.out"

The docs are your friend...

ivans
+2  A: 

The child itself can do select $filehandle to specify that all of its print calls should be directed to a specific filehandle.

The best the parent can do is use system or exec or something of the sort to do shell redirection.

JSBangs
+2  A: 
open my $fh, '>', $file;
defined(my $pid = fork) or die "fork: $!";
if (!$pid) {
    open STDOUT, '>&', $fh;

    # do whatever you want
    ...

    exit;
}
waitpid $pid, 0;
print $? == 0 ? "ok\n" : "nok\n";
codeholic
+2  A: 

A strictly informational but impractical answer:

Though there's almost certainly a more elegant way of going about this depending on the exact details of what you're trying to do, if you absolutely must have dup2(), its Perl equivalent is present in the POSIX module. However, in this case you're dealing with actual file descriptors and not Perl filehandles, and correspondingly you're restricted to using the other provided functions in the POSIX module, all of which are analogous to what you would be using in C. To some extent, you would be writing C in very un-Perlish Perl.

http://perldoc.perl.org/POSIX.html

cikkle
A: 

As JS Bangs said, an easy way to redirect output is to use the 'select' statement.
Many thanks to stackoverflow and their users. I hope this is helpful

for example:

print "to console\n"; 
open OUTPUT, '>', "foo.txt" or die "Can't create filehandle: $!";
select OUTPUT; $| = 1;  # make unbuffered
print "to file\n";
print OUTPUT "also to file\n";
print STDOUT "to console\n";
# close current output file
close(OUTPUT);
# reset stdout to be the default file handle
select STDOUT;
print "to console";