Mr Klein! Very nice. You reminded me that this is actually a perlfaq:
perldoc -q occurrences Interesting that tr/// is so much faster than index() - I wonder why that is? --edan -----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Yossi Klein Sent: Monday, September 03, 2007 14:56 To: Perl in Israel Subject: Re: [Israel.pm] count chars I believe that the recommended fastest way of doing this is $cnt = $string =~ tr/a/a/; Adding: sub c_tr { my ($c) = @_; return $string =~ tr/$c/$c/; } to Edan's benchmarking example (Hi Ephraim), I get: Rate c_regexp c_index c_tr c_regexp 100849/s -- -69% -91% c_index 326938/s 224% -- -70% c_tr 1085603/s 976% 232% -- Yossi ----- Original Message ---- From: Yuval Kogman <[EMAIL PROTECTED]> To: Perl in Israel <[email protected]> Sent: Monday, September 3, 2007 2:42:55 PM Subject: Re: [Israel.pm] count chars You can use the goatse.cx operator: my $matches =()= ( $string =~ /a/g ); This will evaluate the regex in list context and only then coerce it to scalar context. On Mon, Sep 03, 2007 at 13:38:05 +0300, Amir E. Aharoni wrote: > What is the best way to count the number of times that a character > appears in a string? > > Currently i do this: > > ---- > my $string = "abracadabra"; > my @matches = ($string =~ /a/g); > print scalar @matches; # 5 > print "@matches"; # a a a a a > ---- > > Is there a way to do it without the intermediate array? > > This doesn't work: > > ---- > my $string = "abracadabra"; > print scalar ($string =~ /a/g); # prints 1! > ---- > > I can use this: > > ---- > my $matches = ($string =~ s/(a)/$1/g); > ---- > > It replaces the characters with itself and returns the number of > substitutions, but it doesn't improve readability. > > Any other ideas? > > -- > Amir Elisha Aharoni > words: http://aharoni.wordpress.com/ > music: http://www.myspace.com/tzabari/ > _______________________________________________ > Perl mailing list > [email protected] > http://perl.org.il/mailman/listinfo/perl -- Yuval Kogman <[EMAIL PROTECTED]> http://nothingmuch.woobling.org 0xEBD27418 _______________________________________________ Perl mailing list [email protected] http://perl.org.il/mailman/listinfo/perl ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz _______________________________________________ Perl mailing list [email protected] http://perl.org.il/mailman/listinfo/perl _______________________________________________ Perl mailing list [email protected] http://perl.org.il/mailman/listinfo/perl
