in reply to Re: Match a string only once in a file
in thread Match a string only once in a file

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.

Replies are listed 'Best First'.
Re^3: Match a string only once in a file
by hsinclai (Deacon) on Mar 08, 2005 at 04:18 UTC
    Really cool idea - very instructional - thanks!