Opening files in-memory means what?

perl

Solution

It means you can use filehandles to write to and read from scalar variables.

my $var = "";
open my $fh, '>', \$var;
print $fh "asdf";
close $fh;
print $var;          # asdf

Ultimately, this is just One More Way To Do

$var .= "asdf"

but there are contexts where is more convenient or more appropriate to use filehandle paradigms than string manipulation paradigms.

For example, start with this code:

open my $fh, '>', $logfile;
...
print $fh $some_message_to_be_logged;
... 500 more print $fh statements ...
close $fh;

But you know what? Now I'd rather record my log messages in a scalar variable, maybe so I can search through them, manipulate them before they are written to disk, etc. I could change all my `print` statements to

$logvar .= $some_message_to_be_logged

but in this case it is more convenient to just change the `open` statement.

open my $fh, '>', \$logvar

Problem

You can open file handles in-memory ? The in-memory part is unclear to me, what does that mean ? If that means you can use the computer's memory, Isn't it already working like that ?

Original source