in reply to Match a string only once in a file

Here is another way that reads one line at a time and stops early when all strings are found:
# The first part is the same as the original. open IN, $Filename or die "Could not open file $!"; @array = ('file', 'this', 'dog', 'forward'); my %guard; READLOOP: while (<IN>) { foreach $searchstring (@array) { if (m/$searchstring/i) { if (! exists $guard{$searchstring}) { push @stringsfound, $searchstring; last READLOOP if @stringsfound == @array; $guard{$searchstring} = 1; } } } } close IN; # a somewhat nicer output print join(" ",@stringsfound),"\n";

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:10 UTC
    It tidies up nicely and does less searching if you modify the foreach loop:
    foreach $searchstring (grep {!exists $guard{$_}} @array) { if (m/$searchstring/i) { push @stringsfound, $searchstring; $guard{$searchstring} = undef; } }

    Caution: Contents may have been coded under pressure.