Whin3
Whin3

Reputation: 725

perl check a line contains at list one word of an array

I have a file containing a few words, let's take for example this file :

balloon
space
monkey
fruit

I want to check if a string contains at least one of these words. I stored all the words in an array, like this (the file is specified in parameters) :

open my $exampleFile, '<', $ARGV[0];
chomp(my @exampleWords= <$exampleFile>);
close $exampleFile;

Then I use grep to check if one of these words is in the string:

if ( grep( $string, @exampleWords ) ) 
{
    #do something
}   

If I take for example the string this_is_a_balloon_example, the word balloon has been found so I should enter the loop. At the moment, the loop seems to be entered for any string given.

Upvotes: 2

Views: 3522

Answers (3)

Sobrique
Sobrique

Reputation: 53478

grep iterates a list. It can be fairly inefficient as a result.

I would suggest that what you want to do is compile a regex.

my $regex = join "|", @examplewords; 
$regex    = qr/\b($regex)\b/; 

if ( $string =~ m/$regex/ ) { 
    print "There was a match on $1\n";
}

Upvotes: 6

simbabque
simbabque

Reputation: 54323

Perl's grep does not work like the command line utility grep. You're simply checking if $string is true, which is always the case. If you want to check if any of the words in @exampleWords is contained in $string, you need to tell Perl that.

if ( grep { $string =~ m/$_/} @exampleWords ) {
    ...
}

This uses a pattern match.

Alternatively, you could also use index, which returns the position of the first occurrence of the substring, in this case $_, or -1.

if ( grep { index( $string, $_ ) != -1 } @exampleWords ) { 
    ... 
}

The pattern match is easier to read though, and in terms of performance it really doesn't make a difference.

Upvotes: 1

mpapec
mpapec

Reputation: 50637

Your grep is checking for true value, and $string is almost always 'truthy'. What you need is regex which tests if $string matches againts $_,

if ( grep($string =~ /$_/, @exampleWords ) ) 
{
    #do something
}

Upvotes: 5

Related Questions