If you don't already have it, download File::Temp and use it. Really.

With that what you want to do can be done as:

use File::Temp qw(tempfile); my $temp_fh = tempfile(); my $saved_fh = select($temp_fh); eval "print 'Waka waka!'"; seek ($temp_fh, 0, 0); select($saved_fh); $text = join '', <$temp_fh>; print "The text was '$text'\n";
In fact looking at this, you can add error trapping etc while turning this into a function:
use File::Temp; use Carp; # Takes code to be evaled, supresses printing and returns # the text that would have been printed. sub eval_print_trap { my $code = shift; my $temp_fh = tempfile(); my $saved_fh = select($temp_fh); eval($code); select($saved_fh); if ($@) { confess("Evaling \n'$code'\ngave error $@"); } seek($temp_fh, 0, 0); wantarray ? <$temp_fh>: join '', $temp_fh; }
The point being, of course, that the error handling is a Good Thing to add, you now have a piece of reusable functionality which does not assume that STDOUT had been the previous selected default filehandle, and in your code wouldn't you rather see:
my $output = eval_print_trap("print 'Waka waka!'");
than all of the garbage it required?

Caveat programmer: Perl's select will only redirect prints to the default output from Perl code. You will not trap error output, and you will not trap any printing that comes within C code or other programs. Good luck if you plan to call system.


In reply to Re (tilly) 1: codeopen(INPUT, "&lt;INPUT") gives INPUT opened only for output by tilly
in thread codeopen(INPUT, "&lt;INPUT") gives INPUT opened only for output by belg4mit

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.