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