[Israel.pm] count chars

Yuval Kogman nothingmuch at woobling.org
Mon Sep 3 04:42:55 PDT 2007


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
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

-- 
  Yuval Kogman <nothingmuch at woobling.org>
http://nothingmuch.woobling.org  0xEBD27418




More information about the Perl mailing list