User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Perl section within the Software Development category of DaniWeb, a massive community of 429,884 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,339 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Perl advertiser: Programming Forums

count characters in a string

Join Date: Jan 2006
Posts: 221
Reputation: katharnakh is an unknown quantity at this point 
Rep Power: 3
Solved Threads: 20
katharnakh's Avatar
katharnakh katharnakh is offline Offline
Posting Whiz in Training

Re: count characters in a string

  #26  
Apr 14th, 2008
Hi Kavin,
Originally Posted by KevinADC View Post
Your code does not seem to work properly katharnakh. I did not try and determine why. I don't think the "exists" function works on arrays:

exists ${$cnter{$word}}[$index]

like it does on hash keyes:

exists $cnter{$word}{$title}

so that might be a problem.

The program was executing but output was wrong. I realised later that it is important to maintain the indexes of the titles encountered. I have done the changes... I have added %index as global instead of local to else block.
  1. use strict;
  2. use warnings;
  3. open(IN, "readme.txt") or die "ERROR: $!";
  4. open(OUT, ">seeme.txt") or die "ERROR: $!";
  5. my (%cnter, $title, @order, %index);
  6.  
  7. while(<IN>) {
  8. next if (/^\s*$/);
  9. chomp;
  10. my @line = split(/\s+/);
  11. if($line[0] =~ /^=/) {
  12. $line[0] =~ tr/=//d; # remove all the "=" from the section title
  13. $title = "@line";
  14. push @order, $title;
  15. }
  16. else {
  17. tr/,.?!//d for @line; #remove some punctuation
  18. tr/A-Z/a-z/ for @line; #convert all text to lower case so 'Word' and 'word' are the same
  19.  
  20. # a local hash to store { section => its index in the array
  21.  
  22. @index{@order} = (0..$#order);
  23.  
  24. #$cnter{$_}{$title}++ for @line;
  25. ${$cnter{$_}}[$index{$title}]++ for @line;
  26. }
  27. }
  28.  
  29. print OUT join("\t",@order),"\n";
  30. foreach my $word (sort keys %cnter){
  31. print OUT "$word :";
  32. my @t = ();
  33. foreach my $title (@order) {
  34. #push @t, (exists $cnter{$word}{$title}) ? $cnter{$word}{$title} : 0;
  35. push @t, (defined ${$cnter{$word}}[$index{$title}]) ? ${$cnter{$word}}[$index{$title}] : 0;
  36. }
  37. print OUT join("\t", @t),"\n";
  38. }
  39. close(IN);
  40. close(OUT);

Thanks Kavin...
katharnakh.
challenge the limits
Reply With Quote  
All times are GMT -4. The time now is 8:35 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC