Is there a way to get a copy of STDOUT without redirecting STDOUT? I wanted to capture the printouts from a sub that I cannot change. The following code is doing that (my thanks to others on this board for this code):

#!/usr/bin/perl use strict; use warnings; my ($buf); { local *STDOUT; open( STDOUT, '>', \$buf ) or die "Write to buffer failed\n"; mysub(); } print "buffer: $buf\n"; sub mysub{ print "mysub output\n"; }

The sub's printouts go to STDOUT, which is to my screen. Using the above code, STDOUT is redirected to the variable $buf so no printouts go to the screen. I want to be able to get a copy of the data that is going to STDOUT without redirecting STDOUT. In other words, I want the data to go to the variable "$buf" in the above code and to continue to go to the screen. Is there a way to do this?

I could just print the variable $buf after its done too. However, some of data are very big and the sub that I'm trying to capture takes a long time to execute. During that time, no printouts goes to the screen so there's nothing indicating that the program is still executing correctly.

Also, is there a way to capture STDERR at the same time? I mean, can I redirect a copy of STDERR and STDOUT to the same $variable? I was able to do it to two variables, but then, I don't know which error occur when. It would be nice to have the STDOUT and STDERR in the same spot in chronological order so I know which error occurred after which STDOUT data.

Thanks for any help.

MNJ


In reply to Need Help: Capture STDOUT without Redirecting by mnj200g

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.