in reply to Comparing string to array elements

do you have test data?

the code looks good for me,

try to show a minimal working (and intended) example reading text from DATA and having @terms populated.

personally I would code it with something like

$clause= join "|", @terms; print $1 while m/UP($clause)LB/g;

(untested)

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^2: Comparing string to array elements
by R56 (Sexton) on Jan 11, 2017 at 18:55 UTC

    Thank you for the reply Rolf! I'm guessing I should've put all the code instead of a little snippet, as it isn't very long.

    use strict; use warnings; use File::Slurp; my $countfile = 1; open (IN, 'C:\terms.txt'); my @terms = <IN>; close IN; open (OUT,'>>C:\result.txt'); while ($countfile < 10000) { my $text = read_file('C:\file' . $countfile . '.xml') or die "Can' +t open file!"; if($text =~ /upperboundary(.+?)lowerboundary/s){ if(grep {$_ eq $1} @terms) { print OUT "$1\t"; } } close IN; $countfile++; open (IN, 'C:\file' . $countfile . '.xml') or die "End of files!"; } close OUT;

    I can see the array populated if I print it, but there must be some other thing that's destroying the output at the middle...

        Added it, thanks!

      Ok, I was overlooking something. I was comparing a whole set of free text to an array of terms, no wonder why it didn't return anything.

      Can the solution be splitting that free text into an array, and then comparing that to the terms I already have, printing the matches?

      my @adv = split /\s+/, $1;

      How would I compare if each term in @adv matches one on @terms, and then print it if it exists?

        Why not

        • read in the terms.txt file into a scalar variable using slurp,
        • split that into an array of terms,
        • use a regex inside a foreach loop to test each term against your text?

        The example I gave you was intended to point you in this direction. My example shows how to slurp a file into a scalar variable. Then split that with something like my @terms = split ' ', $terms_text.