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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |