Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Re: Re: Re:{2} Getting impossible things right (behaviour of keys)

by blakem (Monsignor)
on Oct 24, 2001 at 22:25 UTC ( #121220=note: print w/replies, xml ) Need Help??

in reply to Re: Re: Re:{2} Getting impossible things right (behaviour of keys)
in thread Getting impossible things right (behaviour of keys)

OK, I'll take you through it... it looks like I misled several others with my late night post as well.

First, lets look at a slightly newer version of the code:

1: my $pattern = join('|',(keys %sufdata)); 2: if ($name =~ s/($pattern)$/$sufdata{$1}/o) { 3: print "Suffix $1 -> $name\n"; 4: return; 5: } 6: print " no rule apply -> $name\n";
Our main goal is to construct a pattern that matches a piece at the end of the string. This match needs to be one of the keys in %sufdata, specifically the longest such key that matches.

So, start with line #1.

my $pattern = join('|',(keys %sufdata));
Here we create a list of keys in %sufdata, then join them together with '|' symbols. $pattern is now a string that looks like "a|s|k|ar|ic|ec|ek|er|vec" though the order of the keys is unknown (and unimportant in this specific case).

In line #2:

if ($name =~ s/($pattern)$/$sufdata{$1}/o) {
If we expand $pattern oursleves, we get:
if ($name =~ s/(a|s|k|ar|ic|ec|ek|er|vec)$/$sufdata{$1}/o) {
We check for a match, and replace the first one we find with the corresponding value from %sufdata.

Now here's the trick... the regex engine works from left to right, checking if *any* of those keys match at each position along the way. Since we are anchored at the end, and we use the first one we find, this effectively becomes a search for the longest matching suffix.

So, because of the "left most matching" behavior of the regex engine, we can feel assured that the first match, will actually be the longest one in this particular instance.

Lines 3-6 are left as an excercise for the reader. ;-)


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://121220]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2016-12-03 18:24 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (56 votes). Check out past polls.