简体   繁体   中英

Perl regex using array as search items

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";
    }
}
if($line =~ /foo|bar|baz/)

or

my @kwarray = qw(foo bar baz);
my $keywords_re = join('|', map { quotemeta $_ } @kwarray);
...
if($line =~ /$keywords_re/o)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM