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; }

In reply to Stream Handles by hsmyers

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.