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

Count the number of character(case insensitive) in a file

P: 6
Hi,

I want to write a perl script to count the number of character(case insensitive) in a file.

let me know if this is write way to do this.
Expand|Select|Wrap|Line Numbers
  1. open(IN,"words.txt");
  2. $count=0;
  3. $char="a";
  4.  
  5. $char=lc($substr);
  6. $char2=uc($substr);
  7.  
  8. while(<IN>)
  9. {
  10.     $result= rindex($_,$char,length($_));
  11.     $result2= rindex($_,$char2,length($_));
  12.  
  13.     while($result!=-1)
  14.     {
  15.         $count=$count+1;
  16.         $result=rindex($_,$char,$result-1);
  17.     }
  18.  
  19.  
  20.     while($result2!=-1)
  21.     {
  22.         $count=$count+1;
  23.         $result2=rindex($_,$char2,$result2-1);
  24.     }
  25.  
  26.  
  27. }
  28. print $count."\n";;
  29. close(IN);
  30.  
  31.  
  32.  
Thanks & Regards
Chendil
Jun 7 '10 #1

✓ answered by chorny

tr/// returns number of characters replaced. You can use this to simplify your program.

eval "$charnum = $str =~ tr/$char/$char/"; # eval is necessary here

Share this Question
Share on Google+
4 Replies


Expert
P: 80
tr/// returns number of characters replaced. You can use this to simplify your program.

eval "$charnum = $str =~ tr/$char/$char/"; # eval is necessary here
Jun 7 '10 #2

Expert
P: 70
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. use warnings;
  3.  
  4. my $char = 'a';
  5. my $tot  = 0;
  6. while (<>) {
  7.     my $num = () = /$char/ig;
  8.     $tot += $num;
  9. }
  10. print "tot = $tot\n";
See also:
Expand|Select|Wrap|Line Numbers
  1. perldoc -q count
Jun 7 '10 #3

P: 6
@toolic
Thanks for quick reply.
Jun 8 '10 #4

P: 6
@chorny
Thanks for the small script.
Jun 8 '10 #5

Post your reply

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