in reply to Using array elements for a file search

I know they are scary at first but this is the kind of thing regular expressions were born for.

The sample code below contains some comments which may help.
use warnings; my @array = qw (A B C D); ## This example uses the open-file-handle-as-string feature ## Substitute \(my ...) for filepath open (my $INFILE,"<", \(my $in = join "\n", qw(aA d DDD CDA e XYZ AABB +CC))); open (my $OUTFILE,">", \(my $out)); ## Create a regular expression for all elements in the array. ## With the contents of array above the string created will be ## A+|B+|C+|D+ ## Note how the '+' is suffixed on at the end because the 'join' inser +ts ## between array elements. my $composite_elements_re = join ('+|',@array) . '+'; ## Turn the string into a real regex with qr. ## The 'x' modifier means you can add comments between the '/'s ## See perlretut etc in the perl documentation my $complete_re = qr/ $composite_elements_re /x ; while (my $rec = <$INFILE>){ ## The g modifier means get all matches. my @matches = $rec =~ /($complete_re)/gx ; ## If there are any matches print them to the output string (via f +ilehandle!) ## Note that '@matches and' forces @matches to be interpreted as a + scalar (single) value. ## An array treated as a scalar returns the number of elements. ## So long as @matches >= 1 the matches will be put in the output. @matches and do { print $OUTFILE @matches }; } close ($INFILE); close ($OUTFILE); ## Change to print to file of your choice - or leave as stdout? print "$out\n"; ## prints ADDDCDAAABBCC

Replies are listed 'Best First'.
Re^2: Using array elements for a file search
by Anonymous Monk on Oct 25, 2011 at 11:46 UTC
Re^2: Using array elements for a file search
by Diffie (Initiate) on Jun 26, 2012 at 13:54 UTC
    Hi, I'm looking for something very similar. I have an array of strings, which I want to match to the end of log file entries. At first I did something similar to the original poster:
    my @zones = `cat zones.txt`; chomp (@zones); open (IN, 'logfile.log'); while (<IN>) { chomp; foreach my $zone (@zones) { if ($_ =~ /$zone$/) { print "$zone match\n"; last; } } } close IN;
    But obviously that's rather inefficient and takes for ever. Could your example, of joining the array to a regular expression string, be modified and used in this case where it needs to match the end of the string?