slloyd has asked for the wisdom of the Perl Monks concerning the following question:

Can someone explain what the following code does? And how it works? I do not understand what 2>&1 | really is doing.
open(RS,"$cmd 2>&1 |");
http://www.basgetti.com

Replies are listed 'Best First'.
Re: Can someone explain how this works?
by atcroft (Abbot) on Jun 12, 2005 at 01:24 UTC

    This executes the command contained in $cmd, using shell redirection techniques to feed the output of STDERR into STDOUT, which is read into this program through the RS filehandle. A fuller description of what is occurring can be found in the documentation for the open() function (which can also be found by executing 'perldoc -f open' on most systems.

    (One additional note-I would hope that $cmd does not come from an untrusted source, such as user input from a web form. If so, then there could be the potential for security issues.)

    Hope that helps.

Re: Can someone explain how this works?
by monarch (Priest) on Jun 12, 2005 at 01:25 UTC
    This line starts a new process. And opens a file handle to the output of that process.

    The 2>&1 line means redirect standard handle 2 to standard handle 1. In other words, take all input that would go to STDERR and redirect it to STDOUT. Why is this beneficial? Well, when you open a process this way only the STDOUT output gets to your Perl program through the opened filehandle. If you want error messages as well you need to redirect the STDERR file handle as has been done here.

Re: Can someone explain how this works?
by davidrw (Prior) on Jun 12, 2005 at 01:26 UTC
    It's bash shell syntax for redirections (see the 'REDIRECTION' section in man bash) that effectively combines STDOUT and STDERR so that they both appear in STDOUT, and thus both go through the pipe, and thus both are available via <RS>. If the 2>&1 was omitted, then <RS> would have only what $cmd outputted to STDOUT, and not anything to STDERR.
    Update: DOH! too slow.. maybe i should have responded before approving :)
      Thank you all for your explanations. I understand much better now.
      http://www.basgetti.com
Re: Can someone explain how this works?
by thcsoft (Monk) on Jun 12, 2005 at 12:55 UTC
    perldoc perlopentut perldoc -f open
    language is a virus from outer space.