http://qs1969.pair.com?node_id=580704

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

I'm dealing with an API that takes a file hanlde to write output to as an argument. The problem is, I need the output right after, and I'd rather not go through the trouble of creating a file just to have to read from it and then delete it afterwards. Is there anyway to redirect a file handle to a scalar, so that when it's written to (e.g., "print $handle $ouptut"), the output ends up in a scalar?

Replies are listed 'Best First'.
Re: Writing to a file handle not attached to a file?
by gellyfish (Monsignor) on Oct 26, 2006 at 08:22 UTC

    With a recent (i.e. 5.8.0 onward) perl you can simply open a filehandle to a reference to a scalar rather than a filename. E.g. :

    my $foo = ""; + open BAR, '>', \$foo; + print BAR "Test test"; close BAR; + print $foo;
    In older perls you might want to see IO::Scalar for instance.

    /J\

Re: Writing to a file handle not attached to a file?
by GrandFather (Saint) on Oct 26, 2006 at 08:28 UTC

    Something like this:

    use strict; use warnings; my $buffer; open my $OUT, '>', \$buffer; print $OUT 'Some text'; close $OUT; print $buffer;

    Prints:

    Some text

    DWIM is Perl's answer to Gödel
Re: Writing to a file handle not attached to a file?
by jdporter (Paladin) on Oct 26, 2006 at 14:31 UTC

    For completeness, you should also know about IO::String, and IO::Stringy (from which you would use IO::Scalar).

    We're building the house of the future together.