471,852 Members | 941 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,852 software developers and data experts.

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. }
Aug 9 '07 #1
2 2130
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;
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.


Aug 10 '07 #2
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};
  3. my %count_of;
  4. foreach my $word (split ' ', $string) {
  5.     $count_of{$word}++;
  6. }
  8. while (my ($word, $count) = each %count_of) {
  9.     print "$word : $count\n";
  10. }
- 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 YellowAndGreen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.