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

Lets say:

@array = ("12G","1G30G,"13G24G");

Is there a system variable that would give the number of G's inside the array?

If not, what's the best way I can get it?
In this case, the result will be 5.

thanx...

Edit by BazB: remove pre tags and add normal formatting.
Retitle from "how many letters in a string".

Replies are listed 'Best First'.
Re: Counting recurring characters within a list of strings.
by sleepingsquirrel (Chaplain) on May 28, 2004 at 20:33 UTC
Re: Counting recurring characters within a list of strings.
by Limbic~Region (Chancellor) on May 28, 2004 at 20:38 UTC
    rhxk,
    Your original title was misleading, but has been edited. You want the total number of X in all the elements of a list. This sub should give you an idea of how to make it general. Since others have complained about not making an effort or possibly being homework, I have obfu'd it a bit.
    sub Count { my $t; for ( @_[1..$#_] ) { ($t) += grep {$_ eq $_[0] } split // } return $t; }

    Cheers - L~R

    Update Modified to reflect title change by editors
Re: Counting recurring characters within a list of strings.
by Anonymous Monk on May 28, 2004 at 20:36 UTC
    @array = ("12G","1G30G","13G24G"); $x += tr/G// for @array; print "$x\n" 5
Re: Counting recurring characters within a list of strings.
by cLive ;-) (Prior) on May 28, 2004 at 20:36 UTC
    # count G's my $count = scalar ( () = ("@array" =~ /(G)/gs)); # or, generic - count letters my $count = scalar ( () = ("@array" =~ /([A-Za-z])/gs));
    cLive ;-)
Re: Counting recurring characters within a list of strings.
by pzbagel (Chaplain) on May 28, 2004 at 20:28 UTC

    Try doing your homework before posting it.

    Seriously, what have you tried so far? This is a fairly easy bit of code.

    Later

Re: Counting recurring characters within a list of strings.
by mifflin (Curate) on May 28, 2004 at 20:33 UTC
    This code...
    @array = ("12G","1G30G","13G24G"); map { $cntr++ if /G/ } @array; print "$cntr\n";
    prints 3

    However, I'd do it the longer way to be more obvious...
    @array = ("12G","1G30G","13G24G"); for (@array) { $cntr++ if /G/; } print "$cntr\n";
    There is not single function (that I am aware of) that does this
    monks?

    Update: looks like I got the answer slightly wrong. My result is the number of array elements that have a G in them.
    One brute force way of doing it (getting the correct answer) might be...
    @array = ("12G","1G30G","13G24G"); $str = join '', @array; $str =~ s/[^G]//g; print length($str), "\n";
    This will correctly print 5