Perl Monk, Perl Meditation | |
PerlMonks |
Re^2: Symbols in regexby AnomalousMonk (Archbishop) |
on Nov 17, 2015 at 14:40 UTC ( [id://1147925]=note: print w/replies, xml ) | Need Help?? |
This approach has a subtle problem. The (?<!\w) and (?=\s|$) look-around assertions (see Look-Around Assertions) used as delimiters are ambiguous. One of the "words" (i.e., 'word word') in the dictionary contains a space, which matches both of the delimiters. The Perl regex alternation is "ordered", i.e., the first match in the alternation is the overall match, not the longest match. The sorting used to generate the regex in the code above is ascending; shorter strings with a common initial group of characters will sort before longer strings. This produces a "shortest first" match in the alternation because the delimiters are ambiguous. If the word 'word' is introduced into the translation dictionary along with the ambiguous 'word word' "word", a mistranslation occurs. This can be fixed by disambiguating the delimiters. Another fix is to build the alternation so that a "longest first" match is performed. In the example below, $rx_A is built from an ascending sort and produces a mistranslation. $rx_D is built from a descending sort that produces a longest-first match and translates properly. (If such a "longest" alternation is used, delimiters can often be dispensed with entirely. In general, I prefer to build "longest" alternations from lists into which ambiguous strings may creep.)
See sort for other ways to produce ascending versus descending sorting. Update: Here's an example where the (reversed) default lexical sort alone is sufficient to produce proper, longest-first translation entirely without delimiters:
Give a man a fish: <%-{-{-{-<
In Section
Seekers of Perl Wisdom
|
|