Search code examples
arraysperlstring-matchingsynonym

Check words and synonyms


I have an array with some words, and another array with words and synonyms. I'd like to create a third array when I find a matchin word between first and second array. I tried with grep but I'm not able to write the code in a proper way in order to get what I want. The problem is that elements in array 1 can be found in array 2 at the beginning but also at the end or in the middle.

Maybe it's easier with an exemple:

@array1 = qw(chose, abstraction);
@array2 = (
"inspirer respirer",
"incapable",
"abstraction",
"abaxial",
"cause,chose,objet",
"ventral",
"chose,objet"
);

The result it should be

@array3 = ("abstraction", "cause,chose,objet", "chose,objet");

Is it right to use "grep"? I'm not able to write a right syntax to solve the problem.. Thank you


Solution

  • You can construct a regular expression from the array1, then filter the array2 using it:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my @array1 = qw(chose, abstraction);
    my @array2 = (
                  "inspirer respirer",
                  "incapable",
                  "abstraction",
                  "abaxial",
                  "cause,chose,objet",
                  "ventral",
                  "chose,objet"
                 );
    
    my $regex = join '|', map quotemeta $_, @array1; # quotemeta needed for special characters.
    $regex = qr/$regex/;
    my @array3 = grep /$regex/, @array2;
    print "$_\n" for @array3;