Graeme McLaren am Mittwoch, 8. Februar 2006 14.53:
> Hi all, I have the following code:

Hi Graeme

> ############# code################

use strict; # forces declaring variables
use warnings;

> @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 });

# 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;
print map "$_\t$hash{$_}\n", sort keys %hash;

hth,
joe

-- 
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