Baron Schwartz's Website
Archives Talks

How to Write to a Perl Variable as if It’s a Filehandle

Published Apr 12, 2009 by Baron Schwartz in Open Source, Programming at https://www.xaprb.com/blog/2009/04/12/how-to-write-to-a-perl-variable-as-if-its-a-filehandle/

This is really cool. I just learned this: you can treat a Perl variable just like a filehandle (read, write, etc).

my $buffer = "";
open my $fh, ">", \$buffer or die $OS_ERROR;
print $fh "hello, world\n";

Now $buffer contains “hello, world\n”. You can do the same kinds of things when reading from a variable.

I knew you could do it with IO::Scalar, but while refreshing my memory on that, I stumbled upon this—who needs IO::Scalar anymore?

This is going to make a lot of tests in Maatkit easier to write.

Baron Schwartz

I’m the founder and CTO of VividCortex, author of several books, and creator of various open-source software. I write about topics such as technology, entrepreneurship, and fitness. More about me.

Story logo

© 2019 Baron Schwartz