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

Hi monks,

I have an array and its value.

@array=("one", "two", "one" "three", "four", "one", "two");

I need hash value like the below i.e. how many times words comes in array.

$hash={"one" => 3, "two" => 2, "three" => 1, "four" => 1}

Can you help me how to get like that.

Thank you.

Replies are listed 'Best First'.
Re: Count of array value into hash
by shmem (Chancellor) on Jul 12, 2006 at 11:29 UTC
    What is your effort so far on this task? homework?
    @array=("one", "two", "one" "three", "four", "one", "two"); | # comma missing ----------+

    Anyways, it's dead simple, and the FAQ entries on arrays will tell you.

    $hash->{$_}++ for @array;

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Count of array value into hash
by prasadbabu (Prior) on Jul 12, 2006 at 11:17 UTC

    Anonymous Monk Try this.

    use strict; use warnings; use Tie::IxHash; my (%hash1); tie %hash1, "Tie::IxHash"; #To maintain the order my @array = ("one", "two", "one", "three", "four", "one", "two"); $hash1{$_}++ for (@array); my $hash = \%hash1; print "$_ => $hash->{$_}\n" for ( keys %{$hash}); #Dereference and pri +nt outputs: -------- one => 3 two => 2 three => 1 four => 1

    I have used Tie::IxHash to maintain the insertion order, if order is not a matter, you can just ignore that. Also tak a look at hash and perlref.
    shmem++

    updated:

    Prasad

A reply falls below the community's threshold of quality. You may see it by logging in.