cklatsky has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Count of patterns in a file without knowing pattern in advance
by choroba (Cardinal) on Jun 07, 2019 at 15:40 UTC | |
|
Re: Count of patterns in a file without knowing pattern in advance
by hippo (Archbishop) on Jun 07, 2019 at 15:44 UTC | |
by cklatsky (Initiate) on Jun 07, 2019 at 18:37 UTC | |
by NetWallah (Canon) on Jun 11, 2019 at 03:06 UTC | |
by roho (Bishop) on Jun 14, 2019 at 13:21 UTC | |
by hippo (Archbishop) on Jun 14, 2019 at 13:41 UTC | |
by haukex (Archbishop) on Jun 14, 2019 at 13:37 UTC |