home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #20 / NN_1992_20.iso / spool / comp / lang / perl / 5818 < prev    next >
Encoding:
Text File  |  1992-09-09  |  1.8 KB  |  57 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!gatech!darwin.sura.net!convex!convex!tchrist
  3. From: Tom Christiansen <tchrist@convex.COM>
  4. Subject: Re: Counting characters that match an arbitrary pattern.
  5. Originator: tchrist@pixel.convex.com
  6. Sender: usenet@news.eng.convex.com (news access account)
  7. Message-ID: <1992Sep10.001301.17119@news.eng.convex.com>
  8. Date: Thu, 10 Sep 1992 00:13:01 GMT
  9. Reply-To: tchrist@convex.COM (Tom Christiansen)
  10. References: <1992Sep9.191438.25772@uvaarpa.Virginia.EDU>
  11. Nntp-Posting-Host: pixel.convex.com
  12. Organization: Convex Computer Corporation, Colorado Springs, CO
  13. X-Disclaimer: This message was written by a user at CONVEX Computer
  14.               Corp. The opinions expressed are those of the user and
  15.               not necessarily those of CONVEX.
  16. Lines: 39
  17.  
  18. From the keyboard of noran!iowa!kburton@uunet.uu.net:
  19. :
  20. :I am sure this is a candidate for FAQ but I didn't see it in the "official"
  21. :perl FAQ list so here it is.
  22. :
  23. :What is the most efficient subroutine that counts the number of characters 
  24. :that match a particular pattern. Currently I have:
  25. :
  26. :       sub countchar
  27. :       {
  28. :                  local($pattern,$string) = @_;
  29. :                  local($count);
  30. :                  local($_);
  31. :       
  32. :                  $count = ($string =~ s/$pattern//g);
  33. :              
  34. :                  return $count;
  35. :       }
  36. :
  37. :
  38. :       printf "Count = %d\n",&countchar('[A-Z]',"abcdEFGH");
  39. :
  40. :Is there a better, more efficient way ?
  41.  
  42.     (assume $_ = string)
  43.     (assume constant pattern)
  44.  
  45.     $count++ while /pattern/g;
  46.  
  47. or in the case of single chars:
  48.  
  49.     $count = tr/A-Z//;
  50.  
  51. --tom
  52. -- 
  53.     Tom Christiansen      tchrist@convex.com      convex!tchrist
  54. > (It's sorta like sed, but not.  It's sorta like awk, but not.  etc.)
  55.   Guilty as charged.  Perl is happily ugly, and happily derivative.
  56.         --Larry Wall in <1992Aug26.184221.29627@netlabs.com>
  57.