469,325 Members | 1,516 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,325 developers. It's quick & easy.

Count substrings from a string

can anyone help me in doing that
Here is the code, where am I going wrong??

Expand|Select|Wrap|Line Numbers
  1. while ($string) {
  2.     foreach $word (@words) {
  3.         @words = split " ", @string;
  4.         $count{$word}++;
  5.     }
  6. }
  7. foreach $word (keys %count) {
  8.     print "$word : $count{$word}\n";
  9. }
  10.  
Aug 9 '07 #1
2 2095
numberwhun
3,503 Expert Mod 2GB
You have a lot going on here, but not necessarily all in the correct order. The first thing that jumps out at me is this:

Expand|Select|Wrap|Line Numbers
  1. @words = split " ", @string;
  2.  
You have that defined inside of your foreach loop, but are using the array @words as an argument to your foreach loop. This, I am afraid, is not possible. You must put that outside of the foreach loop so that it is defined before the foreach loop is entered.

Next, in that code snippet above, you reference @string, but it isn't defined anywhere, but $string is.

Do me a favor please. Clean up your code so that it flows properly and if you could, paste all of your code here if it isn't already. Then, please give a better explanation of exactly what you are wanting to do, along with a sample of the data you are referencing, so we know what we are working with.

Regards,

Jeff
Aug 10 '07 #2
miller
1,089 Expert 1GB
As Jeff pointed out, your current code is mostly nonsense. However, the goal of counting words is a rather simple one. Observe the following example:

Expand|Select|Wrap|Line Numbers
  1. my $string = q{foo bar baz bar bit baz foo bot but bar biz};
  2.  
  3. my %count_of;
  4. foreach my $word (split ' ', $string) {
  5.     $count_of{$word}++;
  6. }
  7.  
  8. while (my ($word, $count) = each %count_of) {
  9.     print "$word : $count\n";
  10. }
  11.  
- Miller
Aug 10 '07 #3

Post your reply

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

Similar topics

1 post views Thread by Leandro Pardini | last post: by
4 posts views Thread by spam | last post: by
7 posts views Thread by Matteo Rattotti | last post: by
8 posts views Thread by girish | last post: by
9 posts views Thread by nick048 | last post: by
2 posts views Thread by Pilcrow | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
reply views Thread by Gurmeet2796 | last post: by
reply views Thread by mdpf | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.