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

hiya, I am trying to write code that compares the total count of each of the letters in a line and stores the most common in $consensus.
$Acount = 4; #I have set these values $Ccount = 3; #eventually they will come #from the program looking at #a line in a file $i=0; $j=1; #############WHICH SCORE IS HIGHEST ?############# @scoring = qw ($Acount $Ccount $Dcount...more letters here); @con = qw (A,C,D...more letters here); print "$scoring[$i] \n"; print "$scoring[$j] \n"; if ($scoring[$i]>$scoring[$j]) { $consensus = $con[$i]; $score = $scoring[$i]; } print "consensus is $consensus with a score of $score \n";
eg. I want this to recognize $Acount is higher than $Ccount and store the letter A in $consensus. However when I print out $scoring[$i] and $scoring[$j] I was hoping to see the numbers 4 and 3 printed, not $Acount and $Ccount.

Should I be using an associative array or something, or is this approach just not gonna work ? Thanx

basm100

Edit by dws to add more <code> tags

Replies are listed 'Best First'.
Re: values within arrays
by fs (Monk) on Feb 28, 2002 at 14:26 UTC
    Personally I would do a hash, but the only reason that this isn't working for you is because you're not setting up @scoring up properly. Using the qw operater there is equivalent to
    @scoring = ('$Acount', '$Bcount', ...etc);
    which means that $Acount and company don't get interpreted as variables, but as literal strings. The code you've got will work with
    @scoring = ($Acount, $Bcount, ...etc);
Re: values within arrays
by jlongino (Parson) on Feb 28, 2002 at 17:46 UTC
    As mentioned by fs, hashes would probably be the best way to go. Here is one way to do it, although I'm not trying to filter out any special characters:
    use strict; my %hash; while (<DATA>) { chomp; my @chars = split ''; for my $char (@chars) { # use the next line if case doesn't matter # $hash{lc $char}++; $hash{$char}++; } print join " ", @chars, "\n"; } my $consensus = ''; for (sort keys %hash) { $consensus = $_ if $hash{$_} > $hash{$consensus}; print "\$hash{$_}: $hash{$_}\n"; } print "\nChar: '$consensus' has the highest count: $hash{$consensus}!\ +n"; __DATA__ aAabbbbcdDeeeeEEefFFffffffffffff zzzzzzzxxxxxxxxxyyYyg
    Output
    a A a b b b b c d D e e e e E E e f F F f f f f f f f f f f f f z z z z z z z x x x x x x x x x y y Y y g $hash{A}: 1 $hash{D}: 1 $hash{E}: 2 $hash{F}: 2 $hash{Y}: 1 $hash{a}: 2 $hash{b}: 4 $hash{c}: 1 $hash{d}: 1 $hash{e}: 5 $hash{f}: 13 $hash{g}: 1 $hash{x}: 9 $hash{y}: 3 $hash{z}: 7 Char: 'f' has the highest count: 13!

    --Jim