Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

matching an array of alternates

by Anonymous Monk
on Jun 23, 2000 at 23:12 UTC ( #19644=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I have an array @latin_am=("Ecuador","Mexico");
The actual array contains 10 countries.
I want to scan a text file for any line that matches /Ecuador/ or /Mexico/ or or any other country in the array.
What is the most efficient way of accomplishing this? Thanks very much.

Replies are listed 'Best First'.
Re: matching an array of alternates
by btrott (Parson) on Jun 23, 2000 at 23:17 UTC
    Build a regular expression that will match those countries, then scan through the file and check each line against it:
    my $regex = join '|', @latin_am; while (<>) { print $1 if /$regex/; }
    This reads from STDIN, so invoke it like this:
    % file
      Just wanted to point out that if the file you're searching has a lot of lines, you can gain some speed by adding the "o" option to the regex; i.e.:
      print $1 if /$regex/o;
      This way, the regular expression only has to be compiled once.

      - Zoogie

Re: matching an array of alternates
by takshaka (Friar) on Jun 24, 2000 at 07:23 UTC
    The pipe-joined monolithic regex isn't terribly efficient.

    The qr// approach described in perlfaq6 (that is, versions of perlfaq6 that ship with Perl 5.005 or later, but not the one on this site) is much faster.

    my @regexes = map { qr/\Q$_/ } @latin_am; while (<>) { for my $regex (@regexes) { if ($_ =~ $regex) { print; last; } } }
Re: matching an array of alternates
by perlmonkey (Hermit) on Jun 24, 2000 at 02:27 UTC
    This should do the trick:
    @latin_am=("Ecuador","Mexico"); $regex = join ("|", @latin_am); open( FILE, 'input.txt' ) or die "input.txt: $!"; @lines = grep { /$regex/o } <FILE>;
    @lines will hold all the lines of the file 'input.txt' that match any of the phrases in @latin_am

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://19644]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2018-03-19 01:47 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (231 votes). Check out past polls.