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

Is there anyway to read and write to a filehandle that isn't associated with a file? I tried this:
print FILEHANDLE "Contents of File"; seek(FILEHANDLE,0,0) @contents = <FILEHANDLE>
But it didn't work. Will I have to open a /tmp file?

Replies are listed 'Best First'.
Re: Reading and Writing Filehandles
by Zaxo (Archbishop) on Feb 05, 2003 at 03:13 UTC

    Do you want to use a perl variable as if it were a file? Previous versions of perl had IO::Stringy and IO::Scalar for that. Perl 5.8 with PerlIO has it natively. Just use a reference to the scalar in the filename slot of open.

    my $foo = ''; open FILEHANDLE, '+>', \$foo or die $!; print FILEHANDLE "Contents of File"; seek(FILEHANDLE,0,0); my @contents = <FILEHANDLE>; close FILEHANDLE or die $!; print 'From $foo: ', $foo, $/; print 'From file read: ', @contents, $/;
    I meditated on this in Open Has a New Trick.

    After Compline,
    Zaxo

Re: Reading and Writing Filehandles
by data64 (Chaplain) on Feb 05, 2003 at 03:13 UTC

    You could use IO::Scalar which seems to be part of IO::Stringy.

    Below code is from the documentation.

    use IO::Scalar; $data = "My message:\n"; ### Open a handle on a string, and append to it: $SH = new IO::Scalar \$data; print $SH "Hello"; print $SH ", world!\nBye now!\n"; print "The string is now: ", $data, "\n"; ### Open a handle on a string, read it line-by-line, then close it +: $SH = new IO::Scalar \$data; while (<$SH>) { print "Got line: $_"; } close $SH;

    Just a tongue-tied, twisted, earth-bound misfit. -- Pink Floyd

Re: Reading and Writing Filehandles
by rob_au (Abbot) on Feb 05, 2003 at 05:59 UTC
    Another direction which you may want to take is to have a look at Using Temporary Files in Perl which discusses at length secure methods for the handling of temporary files, including the creation of anonymous IO streams for the storage of information in just the manner you request.

     

    perl -le 'print+unpack("N",pack("B32","00000000000000000000001000101001"))'