I would use IPC::Open3 for this. You can open two filehandles simultaneously, one for STDOUT and one for STDERR and collect their respective outputs into two separate scalars:

use strict; use warnings; use IPC::Open3; my ($msg_out,$err_out); eval { open3(undef, *OUT, *ERR, @ARGV) }; if ($@) { $msg_out = ''; $err_out = "invalid command '$ARGV[0]'"; } else { $msg_out = do {local $/;<OUT>}; $err_out = do {local $/;<ERR>}; } print "STDOUT: $msg_out\n"; print "STDERR: $err_out\n";
Just run this script and pass the command (and options) you want it to run for you, for example:
./foo.pl ls -la

./foo.pl some_command_that_does_not_exist

./foo.pl perl -le 'die "goodbye cruel world"'
etc. IPC::Open3 does a lot more than just this, be sure and read the docs as you might need to wait for and reap the child process yourself. YMMV. :)

UPDATE: Good point, Aristotle. This code indeed does not record STDOUT and STDERR as they occur, but is that really a reasonable request? Have you ever had need for such? I can't say that i have ... :-/

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)

In reply to Re: STDERR and STDOUT by jeffa
in thread STDERR and STDOUT by Anonymous Monk

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.