in reply to Trying to make a search Part 2


Thanx guys. I got it to work like this:

#!/usr/bin/perl use warnings; print "Search for what: "; chomp(my $search = <STDIN>); @words = split(/ /, $search); open(DATA, "books.txt") or die "error opening file $!"; while (<DATA>) { foreach $word(@words) { chomp($word); if (/$word/i) { print; } } }

But now how would I get it to only print out the entry once even when there are multiple matches

-- zdog (Zenon Zabinski)
   Go Bells!!

Replies are listed 'Best First'.
RE: Re: Trying to make a search Part 2
by swiftone (Curate) on Jun 05, 2000 at 20:05 UTC
    But now how would I get it to only print out the entry once even when there are multiple matches
    Like so:
    #!/usr/bin/perl use warnings; print "Search for what: "; chomp(my $search = <STDIN>); my %found; #used as a set later @words = split(/ /, $search); open(DATA, "books.txt") or die "error opening file $!"; while (<DATA>) { foreach $word(@words) { chomp($word); if (/$word/i) { print unless defined($found{lc($word)}); $found{lc($word)}=1; #indicates that word has been found } } }
    Update: This prints the line for each word only once. If you instead want to print each line only once, regardless of how many words it matches, try this:
    #!/usr/bin/perl use warnings; print "Search for what: "; chomp(my $search = <STDIN>); @words = split(/ /, $search); open(DATA, "books.txt") or die "error opening file $!"; while (<DATA>) { foreach $word(@words) { chomp($word); if (/$word/i) { print; last; #skips checking this line against oth +er words } } }
RE: Re: Trying to make a search Part 2
by Adam (Vicar) on Jun 05, 2000 at 20:05 UTC
    I would use a hash, like this:
    if (/$word/i) { print unless (++$matches{$word} > 1) }
    I suppose you could use $_ in place of $word if you wanted.

    Update: After seeing swiftone's post I realize that I forgot to adjust case. Thanks swiftone.

    if (/$word/i) { print unless (++$matches{lc $word} > 1) }