in reply to Re^4: perl sort issue while going through article at perl.com
in thread perl sort issue while going through article at perl.com

can someone please help me with this? I do not understand why it's not giving me the each counted key.. it's just giving me 1.. what am I missing??
#!/usr/bin/perl -w use strict; use diagnostics; use Data::Dumper; my %hash = ( key1 => 'value1', key2 => 'value2', key3 => 'value3', key3 => 'value3', key3 => 'value3', key1 => 'value3', key1 => 'value33', key1 => 'value3', key1 => 'value3', key2 => 'value3', key2 => 'value3', key2 => 'value3', key4 => 'value3', key4 => '23232', key5 => '23232', key6 => '23232', key6 => '23232', ); my %hist; foreach (sort keys %hash) { $hist{$_}++; } print Dumper(%hist); __END__ foreach (sort keys %hist) { print "$_ => $hist{$_}\n"; } $VAR1 = 'key5'; $VAR2 = 1; $VAR3 = 'key2'; $VAR4 = 1; $VAR5 = 'key6'; $VAR6 = 1; $VAR7 = 'key4'; $VAR8 = 1; $VAR9 = 'key1'; $VAR10 = 1; $VAR11 = 'key3'; $VAR12 = 1;

Replies are listed 'Best First'.
Re^6: perl sort issue while going through article at perl.com
by FunkyMonk (Bishop) on Oct 23, 2007 at 22:57 UTC
    A hash is like an array but the index can be text instead of a number. so when you write
    my %hash = ( key1 => 'value1', key2 => 'value2', key3 => 'value3', key3 => 'value3', key3 => 'value3', key1 => 'value3',

    the second time you do key1 => ... it will overwrite any earlier value of key1.

    There will only ever be one value associated with each key, so when you

    foreach (sort keys %hash) { $hist{$_}++; }

    each key will be unique, so the count will be one for each of them

    You need to study hashes more. Perhaps perldsc will be of help

      thank you so much. I was reading all the perl books going crazy.. but thank you and I will also read perldsc again to make sure I get better understanding. this is huge