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
|