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 } } }

In reply to RE: Re: Trying to make a search Part 2 by swiftone
in thread Trying to make a search Part 2 by zdog

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.