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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chendil
    New Member
    • Mar 2010
    • 6

    #1

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

    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.
    Code:
    open(IN,"words.txt");
    $count=0;
    $char="a";
    
    $char=lc($substr);
    $char2=uc($substr);
    
    while(<IN>)
    {
    	$result= rindex($_,$char,length($_));
    	$result2= rindex($_,$char2,length($_));
    
    	while($result!=-1)
    	{
    		$count=$count+1;
    		$result=rindex($_,$char,$result-1);
    	}
    
    	
    	while($result2!=-1)
    	{
    		$count=$count+1;
    		$result2=rindex($_,$char2,$result2-1);
    	}
    	
    
    }
    print $count."\n";;
    close(IN);
    Thanks & Regards
    Chendil
  • chorny
    Recognized Expert New Member
    • Jan 2008
    • 80

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

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

    Comment

    • toolic
      Recognized Expert New Member
      • Sep 2009
      • 70

      #3
      Code:
      use strict;
      use warnings;
      
      my $char = 'a';
      my $tot  = 0;
      while (<>) {
          my $num = () = /$char/ig;
          $tot += $num;
      }
      print "tot = $tot\n";
      See also:
      Code:
      perldoc -q count

      Comment

      • Chendil
        New Member
        • Mar 2010
        • 6

        #4
        Originally posted by toolic
        Code:
        use strict;
        use warnings;
        
        my $char = 'a';
        my $tot  = 0;
        while (<>) {
            my $num = () = /$char/ig;
            $tot += $num;
        }
        print "tot = $tot\n";
        See also:
        Code:
        perldoc -q count
        Thanks for quick reply.

        Comment

        • Chendil
          New Member
          • Mar 2010
          • 6

          #5
          Originally posted 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
          Thanks for the small script.

          Comment

          Working...