Home > database >  Open a scalar as a file in Perl
Open a scalar as a file in Perl

Time:01-24

According to PerlDoc you can direct a file open to a scalar variable https://perldoc.perl.org/functions/open#Opening-a-filehandle-into-an-in-memory-scalar

I am trying to establish if I can use this approach for a temp file that is persistent within the lexical domain. I am doing the following as a test:

my $memfile;
my $filename=\$memfile;

open (OUT, ">", $filename);
print OUT "some data\n";
close (OUT);

I want to be able to read from the scalar later; eg:

open (IN, "<", $filename);
while (my $in=<IN>)
{
  print "$in\n";
}
close (IN);

This doesn't work, so am I barking mad or is there a right way to do it so it does work?

CodePudding user response:

We can indeed open a filehandle to a variable, and write to it; but then we use it like any other variable, not by opening another filehandle to it

open my $fhv, '>', \my $stdout or die $!;
say $fhv "hi";
close $fhv;

print $stdout;

This works with another "layer" of variables, like in the question, as well,

 my $memfile;
 my $file = \$memfile;
 open my $fhv, '>', $file or die $!;
 say $fhv "hi";
 close $fhv;

 print $memfile;

Note that $fhv isn't quite a proper filehandle and some filehandle-uses will not work.

  • Related