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

Hi Monks,
my $search = "foo"; my @array = ("s1 bar", "s2 notfoo", "s3 foo")
I would like to grep @array for an exact match of $search, if I do
grep {/$search$/} @array
grep will match both the 2nd and 3rd elements of @array as they both end in "foo", is it possible to only return an exact match for the last characters the same size of the search term? Cheers, Chris

Replies are listed 'Best First'.
Re: grep regex exact match last n positions
by NetWallah (Canon) on Apr 13, 2010 at 04:51 UTC
    If you are trying to match a 'word boundary', try \b:
    grep {/\b$search$/} @array

         Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

      thank you.
Re: grep regex exact match last n positions
by ikegami (Patriarch) on Apr 13, 2010 at 04:51 UTC
Re: grep regex exact match last n positions
by jwkrahn (Abbot) on Apr 13, 2010 at 07:22 UTC
    I would like to grep @array for an exact match of $search
    grep {$_ eq $search} @array
Re: grep regex exact match last n positions
by nvivek (Vicar) on Apr 13, 2010 at 05:36 UTC
    If you want to match the string in the array end with same number of characters as the pattern.Then,you try this.
    my $search = "foo"; my $len=length($search); #finding the length of the pattern my @array = ("s1 bar", "foo", "s3 foo"); print grep {/.*\b(.{$len})/;$_=$& if $1 eq $search;} @array; #checking whether the end characters of the string in the array is same as the pattern given
      That's an expensive way of doing substr! Not to mention that your regexp actually doesn't find the last 3 characters - it finds the first 3 characters following the last word boundary.
      print grep {substr($_, -length($search)) eq $search} @array;