in reply to how to count matches

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//);