in reply to Re: If Exists in an Array?
in thread If Exists in an Array?
Is that what you meant to write?
linecnt1++ if grep { /\b$Loco_no\b/ } @loco_data;Doing a hash lookup--like the op was trying to do--is more efficient than searching the entire array every time through the loop. You know, O(n squared) v. O(n) type stuff.
use strict; use warnings; use 5.010; open (my $LOGFILE, "<", "logfile.txt"); open (my $MATCHFILE, "<", "matches.txt"); chomp(my @keys = <$MATCHFILE>); close $MATCHFILE; #Initialize hash: my %target_matches; @target_matches{@keys} = (); #now the keys exist, and the values are undef my($num_records, $match_count) = (0, 0); while (<$LOGFILE>) { chomp; my @fields = split /,/; if (exists $target_matches{$fields[1]}) { $match_count++; } $num_records++; say "Total records: $num_records, matches: $match_count"; } close $LOGFILE;
matches.txt:
1 2 3 4
logfile.txt:
a,5,b,c,d,e a,2,b,c,d,e a,8,b,c,d,e a,3,b,c,d,e
output:
Total records: 1, matches: 0 Total records: 2, matches: 1 Total records: 3, matches: 1 Total records: 4, matches: 2
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: If Exists in an Array?
by keszler (Priest) on Nov 13, 2009 at 13:43 UTC | |
|
Re^3: If Exists in an Array?
by 7stud (Deacon) on Nov 13, 2009 at 10:21 UTC | |
|
Re^3: If Exists in an Array?
by batcater98 (Acolyte) on Nov 13, 2009 at 14:44 UTC | |
by keszler (Priest) on Nov 13, 2009 at 17:10 UTC |