Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Writing to a file handle not attached to a file?

by Anonymous Monk
on Oct 26, 2006 at 08:16 UTC ( [id://580704]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-03-28 09:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found