in reply to Match a string only once in a file

Or..
my @array = ('file', 'this', 'dog', 'forward' ); my $searchstring = join '|',@array; foreach ( @file ) { if ( /($searchstring)/i ) { push @stringsfound,$1 unless grep { $_ eq $1 } @stringsfound; } }

Replies are listed 'Best First'.
Re^2: Match a string only once in a file
by Roy Johnson (Monsignor) on Mar 08, 2005 at 01:19 UTC
    What if "this dog" appears? The pattern will match "this" and move on to the next line. You would need to to a global (/g) match on the line, and then sift through what you found.

    One interesting way to use the superterm approach is to remove each term you find from it as you go:

    my @file = <DATA>; my @array = ('file', 'this', 'dog', 'forward'); my $superterm = join '|', @array; my @stringsfound; my %guard; for (@file) { while ($superterm ne '' and /($superterm)/gi) { print "Found <$1>\n"; # To watch it work push @stringsfound, $1; $guard{$1} = undef; $superterm = join '|', grep {!exists $guard{$_}} @array; } } print map "$_\n", @stringsfound; __DATA__ No one could find this dog dog dog a young boy came forward to claim this file but his file was a mile long

    Caution: Contents may have been coded under pressure.
      Really cool idea - very instructional - thanks!