|
Since |
Ferreira's Home Page |
|
Perl Bit #1: Streaming to a String |
In-memory files can be opened very easily with the module IO::String.
Just like this.
use IO::String;
my $s = <<SQL;
SELECT a, b, c FROM T
WHERE k = ?
SQL
my $io = new IO::String($s);
while (<$io>) {
print;
}
This can be done also with IO::Scalar. None of these methods
are part of Perl standard distribution. But since 5.8, you have in-memory
files for free with PerlIO support. No module needed, you just use
a scalar variable as you would use a handle with the three-arguments
open.
open my $io, "<", $s
or die "can't open in-memory file: $!\n";
Why would you like this? Strings are just as easy to handle in Perl as io handles. But even so, they are treated differently. Turning a scalar into an io handle, you avoid the need for two versions of the same code.