perl - Check if line in datafile contains an array element -
i have file containing list of keywords. have second datafile containing few thousand rows of data. have read file containing keywords array, take first element in array, loop through lines in file , print values contain array element. move onto next element in array , repeat process.
below code far, doesn't seem doing anything. don't know if i'm trying possible. appreciated.
use strict; use warnings; $keywords= shift; $data= shift; #reading in keywords file , storing in array open (fh, "< $keywords"); @keywords= <fh>; close fh; # want iterate on array , each element loop through # datafile checking if element exists in line open (datafile, "< $data"); $element (@keywords) { $line (<datafile>) { if ($line =~ /\q$element\e/) { print $line; } } } close datafile;
first, should check whether file open succeeded , complain appropriately if didn't.
open (fh, "< $keywords") or die "failed open $keywords: $!"; # ... open (datafile, "< $data") or die "failed open $data: $!";
second, @keywords
array consists of strings newline characters @ end, appeared in file. don't want that. instead rid of newlines read file:
chomp(my @keywords = <fh>);
third, after you've read through data file first time through $element
loop, you're @ end of file, , reading again during successive $element
loops return immediately. quickest fix add seek datafile, 0, 0;
bottom of $element
loop. move file pointer start of file can read again.
finally, have been helpful if had given examples of both files' contents , output expected script produce.
another debugging tip: if didn't understand why wasn't getting of matches expected, add print statements this:
for $element (@keywords) { print "starting search <$element>\n"; $line (<datafile>) { print "examining line <$line>\n"; # ... } }
that have shown newline character in $element
, , wouldn't have seen examining line <$line>
after first pass through file.
Comments
Post a Comment