Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I know about using select to make print default to a different file handle, but it is possible to redirect it to some kind of buffer (say, an array, or some type of object)?

I'm developing a Perl/Tk app that uses a Text widget for the main display. The users will have the ability to write their own perl extensions that the app will run. What I'd like to happen is that if the user does a print in their module, instead of going to STDOUT it will actually go to a buffer that gets processed and then displayed on the main display.

Is there a way to trick print into doing something like this?

Replies are listed 'Best First'.
(jeffa) Re: print()ing somewhere else?
by jeffa (Bishop) on Aug 14, 2002 at 15:07 UTC
    How about IO::String?
    use strict; use IO::String; my $buffer = IO::String->new(); select $buffer; print "hello world\n"; print "testing 1 2 3\n"; # then later ... select STDOUT; print ${$buffer->string_ref};

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: print()ing somewhere else?
by JupiterCrash (Monk) on Aug 14, 2002 at 15:37 UTC
    You can do what you want very nicely with IO::Scalar and tie, here is an example:

    use IO::Scalar; tie *STDOUT, 'IO::Scalar', \$buffer; # all stdout will now go to $buffer, ie print "hello world"; untie *STDOUT; print "buffer is $buffer\n\n"