Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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.

Comment on Re: Exact pattern match inside index()
Select or Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://999172]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (13)
As of 2016-05-03 17:28 GMT
Find Nodes?
    Voting Booth?