in reply to Loop through array or filehandle
So if I understand correctly, the data in the new format will all reside in one array, with a single line per element. If so, have a review of this example code. I simply check the reference type with ref, and act accordingly.
My test input file (file.txt) contains:
this is line 1 in fh blah this is line 2 in fh
Code:
use warnings; use strict; my $search = 'blah'; open my $fh, '<', 'file.txt' or die $!; my @lines = ( "this is line 1 of aref\n", "this is line 2 of aref blah\n", ); parse_line($fh); parse_line(\@lines); sub parse_line { my $arg = shift; if (ref $arg eq 'GLOB'){ # file handle while (<$arg>){ if (/$search/){ print; last; } } } elsif (ref $arg eq 'ARRAY'){ # aref for (@$arg){ if (/$search/){ print "$_\n"; last; } } } else { print "unsupported type...\n"; exit; } }
Output:
this is line 1 in fh blah this is line 2 of aref blah
|
|---|