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

Fellow Monks.

I have a created hash key and want to count the number of each names present. I have already created the hash. The problem I am having is extracting the counts.

Example Data

AAA

AAA

ABC

ACC

ACB

Below is my code.

my %name; open(FILE, $ARGV[0]) or die "Cannot open the file: $!"; my $hashkey; my $hashvalue; while (my $line = <FILE>) { if ($line =~ /(\S+)/) { $hashkey = $1; $hashvalue = $line; $name{$hashkey} = $hashvalue; $name{$hashkey}++; } elsif ($line =~ /\S/) { chomp $line; } } foreach my $hashname (keys %name) { print "$_ $name{$_}\n" for keys %name; } close FILE; exit;

pseudo code

if $hashname exists

count{}++

Desired Output

AAA 2

ABC 1

ACC 1

ACB 1

Replies are listed 'Best First'.
Re: Obtaining number of counts per each name in hash
by jeffa (Bishop) on Jul 07, 2015 at 19:20 UTC

    You want to increment the value of the key as each occurrence is found:

    $name{$hashkey}++;
    And then later:
    print "$_ $name{$_}\n" for keys %name;

    You could trim up your code a bit as well:

    if ($line =~ /(\S+)/) { $name{$1}++; }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: Obtaining number of counts per each name in hash
by Monk::Thomas (Friar) on Jul 07, 2015 at 21:41 UTC
    - print "$_ $name{$_}\n" for keys %name; + print "$_ $name{$_}\n" for sort keys %name;
    ;)
Re: Obtaining number of counts per each name in hash
by GotToBTru (Prior) on Jul 07, 2015 at 19:22 UTC

    Where in your code do you count the names? Got to do that first before you print the data.

    Dum Spiro Spero
      thats the difficulty i been having. i dont know where i need to place it. in the if statement or before the print statement.

        If you don't actually count, you can't place it anywhere. You need to fix that first!

        jeffa has given you the answer here; I would have preferred that you actually work for it and learn thereby. If you have questions about what his code does, let us know.

        Dum Spiro Spero