I have file that has this data, but I do not know it in advance:

one two three one five two ten one

I want to count the number of times each of those strings appears in the file. I have a script with a nested loop that reads each line of the file in the outer loop, then the inner loop checks line by line in the same file for a match and prints it out. As you can see from the file, it will check for string "one" three times and (correctly) find it is matched three times. But I do not need to have count again when it encounters the same string it counted before. Hopefully, that explanation makes sense.

#!/usr/bin/perl use strict; use warnings; use IO::File; open (FILE, 'numbers.txt'); my @fileone = <FILE>; close (FILE); open (FILE, 'numbers.txt'); my @filetwo = <FILE>; close (FILE); my $count1="0"; my $line; my $pattern; foreach $pattern (@fileone) { chomp $pattern; foreach $line (@filetwo) { chomp $line; if ($line =~ /$pattern/) { $count1++; #my @elements = split ('~',$line); #my $cmts = $elements[1]; } } print "$pattern appeared $count1\n"; $count1="0"; } $ ./test_v2.pl one appeared 3 two appeared 2 three appeared 1 one appeared 3 five appeared 1 two appeared 2 ten appeared 1 one appeared 3

In reply to Count of patterns in a file without knowing pattern in advance by cklatsky

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.