Files are great, but sometimes you want more flexibility. This code shows how to extend file handles to scalars and arrays without much change to the rest of your code.

Update: modified to allow fopen style modes.

hsm

#!/perl/bin/perl # # ftest.pl -- testbed for stream like IO. use strict; use warnings; use diagnostics; use IO::File; use IO::Scalar; use IO::ScalarArray; my @array; my $line; my $poem = <<"RAW"; In Flanders Fields In Flanders fields the poppies blow Between the crosses, row on row, That mark our place; and in the sky The larks, still bravely singing fly Scarce heard amid the guns below. We are the Dead. Short days ago We lived, felt dawn, saw sunset glow. Loved, and were loved, and now we lie In Flanders fields. Take up our quarrel with the foe; To you from falling hands we throw The torch; be yours to hold it high. If ye break faith with us who die We shall not sleep, though poppies grow In Flanders fields. --John McCrae RAW my $fh = IO::File->new("< test.pl"); while ($line = $fh->getline()) { push @array,$line; } $fh->close(); test(\@array,'r'); test("ftest.pl",'r'); test(\$poem,'r'); sub test { my ($fh,$filename) = streamhandle(shift); while ($line = $fh->getline()) { print $line; } $fh->close(); } sub streamhandle { my $ref = ref(my $filename = shift); my $mode = shift; my $New; my $fh; if ($ref eq 'ARRAY') { $New = sub { IO::ScalarArray->new(@_) }; } elsif ($ref eq 'SCALAR') { $New = sub { IO::Scalar->new(@_) }; } else { $New = sub { IO::File->new(@_) }; } $fh = $New->($filename,$mode) or warn "Couldn't open $filename: $!\n"; return $fh,$ref; }