With that what you want to do can be done as:
In fact looking at this, you can add error trapping etc while turning this into a function: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";
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: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; }
than all of the garbage it required?my $output = eval_print_trap("print 'Waka waka!'");
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, "<INPUT") gives INPUT opened only for output
by tilly
in thread codeopen(INPUT, "<INPUT") gives INPUT opened only for output
by belg4mit
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |