Jack B. Nymbol has asked for the wisdom of the Perl Monks concerning the following question:

I want to have any data that would go to STDOUT, STDERR, STDIN to go to a variable. (Ideally just one variable by duping the file handles, but will settle for something close to what I have here.) What am I doing wrong here? I was expecting to get the error from the bad "system" call.
#!/usr/bin/perl use strict; use warnings; close(STDOUT); close(STDIN); close(STDERR); my $strout; my $strin; my $strerr; open(STDOUT, "+<", \$strout) or die; open(STDIN, "+<", \$strin) or die; open(STDERR, "+<", \$strerr) or die; print STDOUT "Hello this is 1 stdout\n"; print STDERR "Hello this is 1 stderr\n"; print STDIN "Hello this is 1 stdin\n"; system("fin . -name asasdasdasd"); print STDOUT "Hello this is 2 stdout\n"; print STDERR "Hello this is 2 stderr\n"; print STDIN "Hello this is 2 stdin\n"; close(STDOUT); close(STDIN); close(STDERR); open(LOG, ">log") or die; print LOG $strout, $strin, $strerr; close(LOG);
cat log Hello this is 1 stdout Hello this is 2 stdout Hello this is 1 stdin Hello this is 2 stdin Hello this is 1 stderr Hello this is 2 stderr

Replies are listed 'Best First'.
Re: printing to a scalar -- STDIN, STDOUT, STDERR
by almut (Canon) on May 27, 2009 at 23:33 UTC
    I want to have any data that would go to STDOUT, STDERR, STDIN to go to a variable.

    The short answer:  forget it, it doesn't work.

    Reason is that when you open a hande to a scalar, you'll get a perl-internal file handle with no associated system file descriptor (fileno() would give -1).  And only those file descriptors can be inherited/shared across the fork/exec which is being done behind the system() call.  The child process doesn't have access to perl-internal file handles.

Re: printing to a scalar -- STDIN, STDOUT, STDERR
by ikegami (Patriarch) on May 28, 2009 at 00:20 UTC
      Yes I know about IPC, the real issue was to have anything that would go to FD 0,1,2 go to a scalar instead. Looking around I might be able to fiddle with the accumulator, $^A.

        the real issue was to have anything that would go to FD 0,1,2 go to a scalar instead.

        Again, see IPC::Run3 and IPC::Run. That's exactly what the two modules allow you to do.

Re: printing to a scalar -- STDIN, STDOUT, STDERR
by ig (Vicar) on May 28, 2009 at 00:25 UTC