Shreyas Karnik
Shreyas Karnik

Reputation: 4133

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?

Upvotes: 0

Views: 1579

Answers (2)

Luis M Rodriguez-R
Luis M Rodriguez-R

Reputation: 1243

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
}

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

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.

Upvotes: 4

Related Questions