Hi, folks,

I don't quite seem to understand how redirection works. I know that 2>&1 feeds stderr into stdout. I think that adding a pipe after that (2>&1|) pipes the combined output back to the file handle (yes/no?). But how do I test failure of the external command? Seems to me that one would not want to combine stderr with stdout in that case, que no?

Here is an example of what I'm currently doing:
my $cmd = 'someProcess.pl -parm val'; open (CMD, "($cmd | sed 's/^/STDOUT:/') 2>&1|"); while (<CMD>;) { if (!s/^STDOUT://) { exitSub(2," Process failed: $_"); } else { # Split the output of the process into ret chomp; @ret = split; } } close (CMD);
I'm not convinced that this is the best way to do things. For one thing, I'm don't really dig using sed or any other system command, if I don't have to. For another, I've seen examples of code with die if the open fails:
open (CMD, "($cmd | sed 's/^/STDOUT:/') 2>&1|") or die $!;

Currently, I find that if my external process fails or gives warnings, the calling code (first example) lets it fall through. A recent example was when I added use warn to the external script and it started spewing out some warnings. This caused the calling script to fail because of unexpected text in the resulting capture of stdout. If I recall correctly, warnings go to stdout, not stderr, right? How would you handle warnings, then?

If someone could help me understand what is going on, I would appreciate it. I'd rather learn how to fish than be given one.

Thanks.


In reply to Error trapping while capturing stdout by ccarden

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.