Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Exact pattern match inside index()

by kennethk (Monsignor)
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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (12)
As of 2014-12-26 18:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (174 votes), past polls