Think about what you are doing. For every line (the outer loop) you count for every domain, if you find it in that line (the inner loop). You only have one counter ($count) that you reset in the outer loop. That means that your counter only counts occurences in one line (then it gets reset) and it counts all domains together (since it is only one counter

You have two options:

The not-really-good option is to reverse the order of the loops again (like you had it in the beginning) and search the result file for every domain one after another. The disadvantage of that method is that you have to reread that result file again and again (for each domain). If the result file is large your simple script will run for minutes or hours and put a lot of strain on your hard disk.

The better option is to change your second script so that you have more than one counter. In perl this is usually done with hashes. Here the adapted script (I also corrected your use of die):

#!/usr/bin/perl -w use strict; my %count; open(DOMAINLIST,'<domainlist') or die $!; my @list=<DOMAINLIST>; chomp @list; open(RESULT,'<result') or die $!; while(<RESULT>){ my $domain; my $i=0; for (my $line=$_){ chomp $line; while($i<scalar(@list)){ $domain=$list[$i]; chomp $domain; if (/\Q$domain\E/) { $count{$domain}++; } ++$i; }} } close RESULT; foreach my $domain (keys %count) { print "$domain\n"; print "$count{$domain}\n"; }

Note that your script still has limitations. Every domain is only counted once per line of the result file.

PS: You should indent your scripts. Makes them much more readable.


In reply to Re^4: search text file by jethro
in thread search text file by Anonymous Monk

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.