Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count Occurances of string in an array or text file

Status
Not open for further replies.

jess916

Programmer
Aug 26, 2008
11
0
0
US
I have a list of strings that are being extracted by pattern matching. I would like to count the number of times any particular string is repeated. I have no idea whether I should store the strings to an array or print to a text file. Any ideas?

Sample Data
pad1
sigA_1[1]
input
pad2
sigB
output
pad1
sigA_1[2]
input... so the output would be sigA 2 and sigB 1
 
use a hash:
Code:
my %count = ();
while(<>){
   if (/(sig[AB])/) {
      $count{$1}++;
   }
}
foreach $key (keys %hash) {
   print "$key = $count{$key}\n";
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Thanks Kevin. Sorry for not being more specific but I need the code to count the number of signals without specifying the signal name. In other words I have a hash and the code would count the instances were a signal is repeated without knowing a specific signal to look for. Is this possible?
 
Well there has to be something to search for, assuming it is "sig" followed by an uppercase letter(s), maybe:

Code:
my %count = ();
while(<>){
   if (/(sig[A-Z]+)/) {
      $count{$1}++;
   }
}
foreach $key (keys %hash) {
   print "$key = $count{$key}\n";
}

If not then you need to define the requirements in a way that can be understood.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Code:
   }
}
[red]- foreach $key (keys %hash) {[/red]
[blue]+ foreach $key (keys %count) {[/blue]
   print "$key = $count{$key}\n";
}

-------------
Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
oops.... thanks Kirsle

Code:
my %count = ();
while(<>){
   if (/(sig[A-Z]+)/) {
      $count{$1}++;
   }
}
foreach $key (keys %count) {
   print "$key = $count{$key}\n";
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top