jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks
I thought this was easy, however it turned out I was not able to solve it.
Here is the test code
#! /usr/bin/perl use strict; use warnings; my $n = "ABCDABDIDAOFOOFAA" ; my $d = ($n =~ /A/g) ; print "matches $d" ;
Output is
matches 1
In this example I try to find out how many A's are present in the string.
Any suggestion what goes wrong here ?

Thnx a lot
LuCa

Replies are listed 'Best First'.
Re: how to count matches
by merlyn (Sage) on May 04, 2007 at 14:42 UTC
    You're using the $n =~ /A/g construct in a scalar context. In a scalar context, it moves only one position to the "next" match, and returns the success of the match.

    If you want to get all the matches, you need to use list context. One ugly way to do that is:

    my $d = () = ($n =~ /A/g);
    But if you're just counting a single character, use tr/// because it'll be much faster:
    my $d = ($n =~ tr/A//);
Re: how to count matches
by ferreira (Chaplain) on May 04, 2007 at 14:47 UTC

    When you did

    my $d = ($n =~ /A/g)
    the global match (triggered by /g) was done at scalar context. In this case it finds a single match or fails. So $d will return 1 or 0.

    To do what you want, you need to set a list context and then count the matches.

    my $n = "ABCDABDIDAOFOOFAA" ; my @matches = ($n =~ /A/g); my $d = @matches; print "matches $d";
    will output "matches 5".
      doesn't work :(
Re: how to count matches
by j1n3l0 (Friar) on May 04, 2007 at 15:26 UTC
    You can also count all the letters this way:
    #!/usr/bin/perl -w use strict; my $string = q<ABCDABDIDAOFOOFAA>; my %count; for (split(//, $string)){$count{$_}++;} print(q<Matches >, $count{A}, "\n");
    This way you can choose which letter's count you wish to view ;)