Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best Match between keys in a hash

Status
Not open for further replies.

user2base

Technical User
Oct 16, 2002
29
0
0
GB
I want to match all the lines of a file against keys in a hash so that there is a match if the line begins with a key. In order to do that I have created a regex that is a join off all the keys separated by "|"

my $regex = join('|', keys %hash);

then I use the following pattern matching:

if ($line =~ /^($regex)/) {
do something;
}

My problem is that different keys can begin with the same word(s). For instance:
key1 = "aaa bbb ddd"
key2 = "aaa ccc"
key3 = "aaa bbb eee"
key4 = "aaa bbb eee fff"

How to dissociate between these keys ??

Thanks.
 
from the list above, what regexes do you need? Mike

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
In this case my regex would be sthg like:

$regex = "aaa bbb ddd|aaa ccc|aaa bbb eee|aaa bbb eee fff";

And I would like a line starting with "aaa ccc ..." to match the 2nd key not the the first one just because it starts with "aaa" because the action will differ for those 2 keys.

Hope it's clear enough.
 
if you join it all into an 'or'ed statement then there is no way of determining which part of the 'or' that the line matched. if you want to know which key matched you will have to loop through the keys and save the key that matches. You will want to sort the keys in reverse order to match the correct key (i.e. a longer key that contains in it a shorter key).

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top