dirtdog has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, i'm hoping there is a better way to check for my value from an Array of hashes. The flaw in the sample code is that i'm grepping through the values for the word SWIM and in the values is the word SWIMMING so it thinks there was a match. Is there a way to tweak it so it only finds an exact match in this scenario?

#!/usr/bin/env perl use warnings; use strict; use Data::Dumper; my $state= 'OHIO'; my %region_of_state; my @events; while (<DATA>) { chomp; next if /^\s*$/ || /^\#/; my $aref = [split /,/, $_]; foreach ($aref->[2]) { print "event = $_\n"; print "region = $aref->[1]\n"; push( @{$region_of_state{$aref->[1]}}, $_) if ($aref->[0] eq $ +state); } } my $event = 'SWIM'; my $region_of_state = 'NE'; if (@events = grep /$event/, @{ $region_of_state{$region_of_state}}) { print "Found a match\n"; } else { print "No Match\n"; } #print Dumper(\@events); #print "@events\n"; __DATA__ OHIO,NE,SWIMMING SWIMMER CLOCK OHIO,SW,BASEBALL PLAYER BATTER

Any help is greatly appreciated. DD

Replies are listed 'Best First'.
Re: matching whole words only
by kennethk (Abbot) on Feb 26, 2015 at 21:48 UTC
    The easiest solution is to use word boundaries:
    if (@events = grep /\b$event\b/, @{ $region_of_state{$region_of_state} +}) {
    Given your approach, you might also want to add quotemeta support:
    if (@events = grep /\b\Q$event\E\b/, @{ $region_of_state{$region_of_st +ate}}) {

    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

      bounderies worked like a charm. Thank you!

Re: matching whole words only
by LanX (Saint) on Feb 26, 2015 at 21:50 UTC
    Better Title?

    try /^SWIM$/

    update

    I've been messaged that I misread your question, so I read it again and must admit you miswrote the question.

    For me its not clear what you really want, hence I shouldn't have answered at all, sorry ;)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)

    PS: Je suis Charlie!

    update

    Original title was "Better Way?" and was corrected after consideration.

Re: matching whole words only
by toolic (Bishop) on Feb 26, 2015 at 21:48 UTC
    I misread the question. Nothing to see here.

    Use eq instead of a regex. Change:
    if (@events = grep /$event/, @{ $region_of_state{$region_of_state}}) {

    to:

    if (@events = grep { $_ eq $event } @{ $region_of_state{$region_of_sta +te} }) {