By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,252 Members | 1,346 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,252 IT Pros & Developers. It's quick & easy.

Getting Info from Array

P: 48
Hi

I have a array in which I need to count the number of ocurrence of a particular word
for eg I need to count no of times a word "test" , "test2" occurs in a array @list.
(The contents of the array is around 100 lines)

Code:
Expand|Select|Wrap|Line Numbers
  1. open(FH3, "sample.txt");
  2. while(<FH3>)
  3. {
  4. @array=$_;
  5. print @array;
  6. }
  7. close(FH3);
  8. my %counts = ();
  9. for (@array) {
  10.    $counts{$_}++;
  11. }
  12. foreach my $keys (keys %counts) {
  13.    print "$keys = $counts{$keys}\n";
  14. }
  15.  
  16.   if($counts{$keys}==1)
  17.         {
  18.       print "$keys = $counts{$keys}\n";
  19.         }
  20.  
I dont want the count for all the words in the array and I need the same only for a given Input word...

Can you help me in this regard..

Thanks In Advance
Mar 14 '08 #1
Share this Question
Share on Google+
2 Replies


nithinpes
Expert 100+
P: 410
The script you have used is very confusing to understand your objective as per the description. Is that the file sample.txt contains one word per line which you are trying to pass to an array? In that case, you can achieve it without the need of the array:

Expand|Select|Wrap|Line Numbers
  1. open(FH3, "sample.txt");
  2. while(<FH3>)
  3. {
  4. chomp;
  5.  $seen{$_} ++ ;
  6. }
  7. print "enter the string that you want to search:";
  8. chomp($str=<STDIN>);
  9. print "$str occurs $seen{$str} times";
  10.  
  11.  
OR, is that you have text file with multiple lines and you need to split each line into words and push it into array for search? For this you can use:

Expand|Select|Wrap|Line Numbers
  1. open(FH3, "cookies.txt");
  2. while(<FH3>)
  3. {
  4. chomp;
  5.  push @a, split(/\s+/,$_); ##split on spaces
  6. }
  7. my %seen =();
  8. $seen{$_}++ foreach(@a);
  9. print "enter the string that you want to search:";
  10. chomp($str=<STDIN>);
  11.  
  12. print "$str was found $seen{$str} times";
  13.  
Mar 14 '08 #2

KevinADC
Expert 2.5K+
P: 4,059
This is just wrong (in the original code):


Expand|Select|Wrap|Line Numbers
  1. open(FH3, "sample.txt");
  2. while(<FH3>)
  3. {
  4. @array=$_;
  5. print @array;
  6. }
unless the file only has one line. Otherwise @array will be populated only with the value of the last line of the file.
Mar 14 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.