How can I redirect standard output to a file in Perl?

后端 未结 5 1626
青春惊慌失措
青春惊慌失措 2020-12-17 18:07

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 f

相关标签:
5条回答
  • 2020-12-17 18:10
    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";
    
    0 讨论(0)
  • 2020-12-17 18:11

    From perldoc -f open:

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

    The docs are your friend...

    0 讨论(0)
  • 2020-12-17 18:17

    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"; 
    
    0 讨论(0)
  • 2020-12-17 18:24

    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.

    0 讨论(0)
  • 2020-12-17 18:31

    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

    0 讨论(0)
提交回复
热议问题