Searching with Hash in Perl
I am using a hash containing 5000 items to match words in a sentence, it so occurs that when I match for eg:开发者_开发百科 if($hash{$word}){Do Something}
sometimes it happens that the period occurs in the word and even if it is a match the presence of period results in a non-match. Can anything be done to ignore any punctuations when matching with hashes?
You would have to redefine the words you look up to exclude the punctuation, remembering that you might or might not want to eliminate all punctuation (for example, you might want to keep dashes and apostrophes - but not single quotes).
The crude technique - not recognizing any punctuation is:
$key = $word;
$key ~= s/\W//g; # Any non-word characters are removed
if (defined $hash{$key}) { DoSomething; }
You can refine the substitute command to meet your needs.
But the only way to make sure that the hash keys match is to make sure that the hashed key matches - so you need to be consistent with what you supply.
Try:
my $s = $word;
$s =~ s/\W//g;
my $k;
for (keys %hash){
s/\W//g;
if($_ eq $s){
$k = $_;
last;
}
}
if(defined $k){
# Do Something
}
精彩评论