Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Exact pattern match inside index()

by kennethk (Abbot)
on Oct 15, 2012 at 20:27 UTC ( #999172=note: print w/replies, xml ) Need Help??

in reply to Exact pattern match inside index()

index does a check for literal characters. By specifying you want CAT but not CATALOG, you are adding criteria that cannot be expressed using literal characters only. You could get closer by using $KEY = " CAT ", since your string is whitespace delimited, but this would fail if CAT is either your first or last entry.

The only way to implement this robustly would be to use a tool that can check for non-literal character criteria, e.g. regular expressions. For example, you could use the word anchor \b to specify you want word boundaries on either side of CAT -- see Using character classes. You can then use $-[0] (see @-) to learn the position of that match. So you might say

my $string = "CATALOG SCATTER CAT CATHARSIS"; my $key = 'CAT'; $string =~ /\b\Q$key\E\b/; print "$key found at $-[0]\n";

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://999172]
[1nickt]: Gotya.
[LanX]: hmm reviews have no vote button?
[1nickt]: I use many books for purposes other than that for which they were written: decoration, paperweight, coffee mug coaster on the good table ...
[LanX]: ah Vote button missing on Review threads

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2017-11-17 21:48 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (274 votes). Check out past polls.