#!/usr/bin/perl use strict; use warnings; my @requiredMatches = ('word1', 'word2', 'word3'); my @testArray = qw (word2 abc word3 xyz word2 asdf word1 word2); my %requiredMatches; # set up a hash table to count occurences of # each word that is required to be there. # Start with "zero", haven't seen it yet. foreach my $requiredWord (@requiredMatches) { $requiredMatches{$requiredWord}=0; } # Now for each word in the input @testArray, increment it's # "seen" count, if and only if it is one of the words # that is being "tracked" meaning that a hash entry exists in # %requiredMatches for that word, i.e., $requiredMatches{$word} # # If you don't check for "exists", Perl will happily create a new # hash entry that is incremented. We don't want that here. # We only want the %requiredMatches hash to contain only the # "must have" words. Update: Well the "if" is not absolutely # required below because we are only going to count "zeroes", # but I prefer this formulation that doesn't generate unnessary # hash entries. foreach my $word (@testArray) { $requiredMatches{$word}++ if exists $requiredMatches{$word}; } # If every hash table entry got incremented (no zero initial # values left), then every required Word was seen at least once. my $countWordMissing=0; foreach my $requiredWord (keys %requiredMatches) { $countWordMissing++ if ($requiredMatches{$requiredWord} == 0); } print "testArray contains all words\n" if $countWordMissing==0;
In reply to Re: Check array for several matches
by Marshall
in thread Check array for several matches
by Bman70
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |