I have a perl module, let's say its called Library.pm, and it contains a lot of subroutines. Some of these subroutines do not return anything, but just print something out. For example I have a subroutine printInformation() that just prints info to STDOUT. eg,
package Library.pm printInformation() { print(STDOUT, "Here is some info, damn its not returning a scalar"); }
The problem with the above subroutine example is that I want to hold on to the string that gets printed to STDOUT (or STDERR), but I cannot modify Library.pm. So instead I need to write LibraryWrapper.pm that massages the subroutines of Library.pm to have returnable scalars, arrays, or hashes, etc. . Below demonstrates what I am trying to do:
package Library.pm use Library.pm printInformationWrapper() { my @captureSTDOUT; my @captureSTDERR; # Set state so that: # @captureSTDOUT is populated with all STDOUT. # @captureSTDERR is populated with all STDERR. printInformation(); # Set state back to previous if (@captureSTDOUT > 0) { # Deal with it. } return @captureSTDOUT; }
Please also bear in mind that I would like a solution that is portable for any platform, and is completely self-contained, ie. all done in one process, (no forks). Lastly, just in case, I know about the backticks operator but it only seems to work on system commands, or more generally commands from the parent environment. It does not work when one perl subroutine calls another in the same process. I'd appreciate the help a lot, thanks.

In reply to In a perl sub, how do I capture STDOUT, STDERR that comes from another perl sub? by seank

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.