I do not know if this is any better for your purpose, but you could create an iterator so that the loop uses the iterator and does not care where the data comes from (the iterator handles that part)
Just a quick example:
use warnings;
use strict;
open my $fh, '<', 'file.txt' or die $!;
my @lines = (
"this is line 1; foo \n",
"this is line 2: bar \n",
"this is line 3: foobar \n",
);
sub create_iter {
my $arg = shift;
if (ref $arg eq 'GLOB') {
return sub {<$arg>};
}
elsif (ref $arg eq 'ARRAY') {
my $index = 0;
return sub {$arg->[$index++]}
}
else { die "Unknown type\n"}
}
print "PRINTING FROM FH\n";
parse_line($fh);
print "\n\nPRINTING FROM ARRAY\n";
parse_line(\@lines);
sub parse_line {
my $arg = shift;
my $iter = create_iter($arg);
while (my $val = $iter->()) {
print $val if $val =~ /foo/;
}
}
This prints out this:
PRINTING FROM FH
this is line 1; foo
this is line 3: foobar
this is line 4; foobaz
PRINTING FROM ARRAY
this is line 1; foo
this is line 3: foobar
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.