Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone,

In the code below, I wanted to say a word in @inputs is matched to what word in @list. How do I get the word in @list that matches the word in @inputs? That is, how do I replace the ?? with the matched word in @list?

use String::Approx qw(amatch); my @list = qw(Apple Pear Orange); my @inputs = qw(aple appe peay range oranges mango appple aqqple); for my $word (@inputs) { if (amatch($word, ["i"], @list)) { print "Matched: $word to ?? <br />"; } else { print "Unmatched: $word <br />"; } }
Sample output: Matched: aple to ?? Matched: appe to ?? Matched: peay to ?? Desired output: Matched: aple to Apple Matched: appe to Apple Matched: peay to Pear

Thank you for reading and looking forward to your replies.

Replies are listed 'Best First'.
Re: Getting matched word from String::Approx
by Athanasius (Archbishop) on Dec 30, 2015 at 12:30 UTC

    There could be more than one word matched, so try this:

    #! perl use strict; use warnings; use String::Approx qw(amatch); my @list = qw(Apple Pear Orange); my @inputs = qw(aple appe peay range oranges mango appple aqqple); for my $word (@inputs) { my @matches = amatch($word, ['i'], @list); if (@matches) { print "Matched: $word to: ", join(', ', @matches), "\n"; } else { print "Unmatched: $word\n"; } }

    Output:

    22:27 >perl 1501_SoPW.pl Matched: aple to: Apple Matched: appe to: Apple Matched: peay to: Pear Matched: range to: Orange Matched: oranges to: Orange Unmatched: mango Matched: appple to: Apple Unmatched: aqqple 22:27 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Many thanks Athanasius ))

      So amatch tries to match every word in @list even after one has been found? If the list is huge, would it be very slow?

      If we just wanted to get the first match from @list and return the result, is there a way to do that?

        If the list is huge, would it be very slow?

        Quite possibly. There’s a discussion in String::Approx#CONTROLLING-THE-CACHE about the tradeoffs between memory and running time.

        If we just wanted to get the first match from @list and return the result, is there a way to do that?

        From the documentation, this doesn’t seem to be possible, no. :-( When called in scalar context, the amatch function returns a single value, but that value is just true or false to indicate whether or not any matches were found.

        Note: Before committing to this module, you should read String::Approx#DESCRIPTION carefully and consider the alternatives. Depending on your requirements, a module such as Text::Levenshtein might suit you better.

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,