Dear Monks,

I am stuck at a matching problem. I have an array which contains a list of terms and their translations, and I want to check if a word is contained in a string of text. I loop my array, and if a match is found I print out the translation. This is an example of my array:

my @dic= ( ['animal source food','aliment d’origine animale'], ['balanced diet','régime alimentaire équilibré'], ['food','aliment'], ['nutrition','nutrition'], ['nutrition assessment','évaluation de l’état nutritionnel'] );

I perform my matching with the following basic script (being $string my string of text:

foreach my $row (@glossary){ my $TermDBSource=@$row[0]; my $TermDBTarget=@$row[1]; if ($string=~ /$TermDBSource/){ print "$TermDBTarget\n"; last; } }

So far so good. My requirement is to match the longest n-gram. As I use a loop, the first match found in my array will be displayed. This could be a problem in a case where $string='this is a nutrition assessment' as it will match first 'nutrition' and not 'nutrition assessment' as desired. If I take out last it will match both 'nutrition' and 'nutrition assessment', again no good. The only idea I came up with is to order my array alphabetically (easy to do) and by length of n-gram (need to look at how to solve it, but I found https://perlmonks.com/?node_id=1219394 which may help me).

My question is more on the approach. Do you think this is the right approach, or I am complicated things too much and there are other more straightforward methods to achieve my goal?


In reply to Matching wirth ordered array by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.