Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: stdout question

by trantor (Chaplain)
on Nov 26, 2001 at 02:17 UTC ( #127434=note: print w/replies, xml ) Need Help??


in reply to stdout question

From what I understand, you want to eval a snippet of perl code in the current context (e.g. package, lexicals, etc.) and capture its STDOUT.

Backticks do not allow you to do it, even though you can execute perl code in that way and capture STDOUT with no problems thanks to the backtick interpolation.

If you use tie and IO::Scalar, you can actually execute a piece of perl code through eval and capture one or more of its filehandles. Basically using tie (reading perltie first) is a powerful way for achieving this and many other "fancy" results.

This is an example of code:

#!/usr/bin/perl -w use strict; use IO::Scalar; my $code = 'print "Hello, world!"'; my $buffer; tie *STDOUT, 'IO::Scalar', \$buffer; eval($code); untie *STDOUT; print "The captured STDOUT is: >>>$buffer<<<\n";

Using Super Search, it is possible to find other useful threads like capturing STDOUT.

Also note that this leads to major security issues, i.e. if your code is not carefully constructed/screened before being evalled.

UPDATE: fastolfe came first using IO::Scalar but he's using select ;-)

-- TMTOWTDI

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://127434]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2023-12-11 13:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (41 votes). Check out past polls.

    Notices?