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

I want to open a filehandle, which writes to a new variable (because I don't want the data to be kept) which will be used in additional steps. Perl doesn't seem to like this. It works fine if I use an existing, external file (which I don't want to use). Is there a way to do this? Dgeminizer@aol.com

Replies are listed 'Best First'.
Re: write from filehandle to variable
by ikegami (Patriarch) on Nov 21, 2005 at 17:39 UTC
    use 5.008000; # Requires Perl 5.8.0 or higher my $var = ''; open(my $fh, '>', \$var) or die("Unable to open mem file: $!"); print $fh 'moo!'; print(length($var), "\n"); # Prints '4'.

    In earlier versions, IO::Scalar might do the trick.

      Thank you for the reply..........I'm pretty green at this. I'm not quite sure which parts of your reply I am to substitute my own names, or files for (i.e. $fh 'moo!', etc.). Could you clarify? Which parts of your code other than the variable name, would I change?
        use if $] < 5.008, 'IO::Scalar'; # IO::Scalar is needed in pre-5.8 Perl my $var = ''; # this is the variable we will be writing to or readi +ng from my $fh; # this is a filehandle, reads and writes will go to $ +var if ($] < 5.008) {$fh = new IO::Scalar \$var} else {open $fh, '+<', \$var} $fh or die "can't get filehandle for \$var: $!"; print $fh "These print statements will\n"; print $fh "be appended to \$var.\n"; seek $fh, 0, 0; # reading and writing <$fh> will seek in $var. my $var1 = <$fh>; my $var2 = <$fh>; print $var1; # print "These print statements will\n" print $var2; # print "be appended to \$var.\n"

        If I understood your original question correctly, you wanted a file handle which wrote to a variable instead of to a file.

        $fh is the file handle.
        $var is the variable in which the text ends up.
        'moo!' is the text being written to $var.