Xaprb

Stay curious!

How to write to a Perl variable as if it’s a filehandle

with one comment

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.

Written by Xaprb

April 12th, 2009 at 1:53 pm

Posted in Coding,Maatkit,Perl

One Response to 'How to write to a Perl variable as if it’s a filehandle'

Subscribe to comments with RSS

  1. Yup, since Perl 5.8.

    fenway

    14 Apr 09 at 2:40 pm

Leave a Reply