home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.perl
- Path: sparky!uunet!gatech!darwin.sura.net!convex!convex!tchrist
- From: Tom Christiansen <tchrist@convex.COM>
- Subject: Re: Counting characters that match an arbitrary pattern.
- Originator: tchrist@pixel.convex.com
- Sender: usenet@news.eng.convex.com (news access account)
- Message-ID: <1992Sep10.001301.17119@news.eng.convex.com>
- Date: Thu, 10 Sep 1992 00:13:01 GMT
- Reply-To: tchrist@convex.COM (Tom Christiansen)
- References: <1992Sep9.191438.25772@uvaarpa.Virginia.EDU>
- Nntp-Posting-Host: pixel.convex.com
- Organization: Convex Computer Corporation, Colorado Springs, CO
- X-Disclaimer: This message was written by a user at CONVEX Computer
- Corp. The opinions expressed are those of the user and
- not necessarily those of CONVEX.
- Lines: 39
-
- From the keyboard of noran!iowa!kburton@uunet.uu.net:
- :
- :I am sure this is a candidate for FAQ but I didn't see it in the "official"
- :perl FAQ list so here it is.
- :
- :What is the most efficient subroutine that counts the number of characters
- :that match a particular pattern. Currently I have:
- :
- : sub countchar
- : {
- : local($pattern,$string) = @_;
- : local($count);
- : local($_);
- :
- : $count = ($string =~ s/$pattern//g);
- :
- : return $count;
- : }
- :
- :
- : printf "Count = %d\n",&countchar('[A-Z]',"abcdEFGH");
- :
- :Is there a better, more efficient way ?
-
- (assume $_ = string)
- (assume constant pattern)
-
- $count++ while /pattern/g;
-
- or in the case of single chars:
-
- $count = tr/A-Z//;
-
- --tom
- --
- Tom Christiansen tchrist@convex.com convex!tchrist
- > (It's sorta like sed, but not. It's sorta like awk, but not. etc.)
- Guilty as charged. Perl is happily ugly, and happily derivative.
- --Larry Wall in <1992Aug26.184221.29627@netlabs.com>
-