1

I am trying to search a file for a given word and return the whole line.

If i specifically define the word such as below, it works perfectly however I want to use a array of keywords that can be used for the regex how would I go about doing this?

The keywords used are from a text file stored as

Hello
Cat
Dog

They are called using the code:

$words = '/computer/textfile';       
open(WORDS, $words);                
@wordarray =  <WORDS>;

This works:

while($line = <FILE>) {   
    if($line =~ /Hello/) {
        print "$line\n";
    }
}

This does not work:

while($line = <FILE>) {
    if($line =~ @wordarray) {
        print "$line\n";
    }
}

1 Answer 1

4
if($line =~ /foo|bar|baz/)

or

my @kwarray = qw(foo bar baz);
my $keywords_re = join('|', map { quotemeta $_ } @kwarray);
...
if($line =~ /$keywords_re/o)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I implemented your example but the problem I have is that I cant use multiple keywords, a single keyword works fine. but i cant do multiple as it is treated as a single string. I planned to use multiple keywords which is why im using an array.
My solution indeed does work with multiple keywords (foo, bar and baz): if any of them match $line, the if body will be executed. Do you need something else?
@pts: The array example won't work as originally posted because it joins the keywords with ' ' instead of '|'. Fix that typo and it should work for the OP.
@user3423572 - Actually, won't work at all the way you are going to use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.