use strict; # forces declaring variables
use warnings;

yep yep :)

@cpv_codes=('a','a','a','a','b','b','b','c','c','d');


my @letters=(qw{ a a a a b b b c c d });

No neeed for the (), which also make sit easier to write and to look at :)

# qw (quote words) makes it easier to write and to look at :-)


my %hash;
foreach (@letters) {
   $hash{$_}++;
   print "$_\t $hash{$_} \n";
}
################################

and it prints:

a        1
a        2
a        3
a        4

[...]

d        1


The reason for that is that you print $hash{$_} *while* building it. What you see is how many times the just found char (in $_) has been seen in the array from its beginning to the current position.


What I really need is:

a = 4
b = 3
c = 2
d = 1


Apart from Jeff's solution, there is also a shorter way:

$hash{$_}++ for @letters;

Good point, better than the map{} I just sent

print map "$_\t$hash{$_}\n", sort keys %hash;

Not sure why you're using map here?

print "$_\t$hash{$_}\n" for sort keys %hash;

Also since strict and warnings have been recommended I might also poitin outthat %hash is a *very* bad name for a hash, its very ambiguouse and hard to maintain, The entire thing is clearly written as:

#!/usr/bin/perl

use strict;
use warnings;

my %letter_count;
my @letters = qw(a a a a b b b c c d T M B G R O C K S);

$letter_count{$_}++ for @letters;

print "$_\t$letter_count{$_}\n" for sort keys %letter_count;


Of course if you really wanted to get strict your 1st for() loop would check that the character is indeed a letter, that its one character, and only then add it to the hash with the ++ :) (and also does case matter? it'd need to handle that too)

So for instance to treat upper and lowercase the same (IE 't' is considered the same as 'T')

for my $letter(@letters) {
    $letter_count{ lc($letter) }++ if lc($letter) =~ m{^[a-z]$};
}


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to