in reply to Convert XML to Hash

Store the values in an anon array as the value of the hash at that key. When you encounter a key,
  1. read the array at that value if it exists,
  2. push the new value onto the end of the array,
  3. then write it back to the value of the hash.
The size of the anon array is the number of times that key appeared, and you can also easily extract the number of unique values.

Replies are listed 'Best First'.
Re^2: Convert XML to Hash
by graff (Chancellor) on Mar 31, 2005 at 03:32 UTC
    Actually, your step "2" is the only one that's necessary:
    # for a simple case, where input is just a "key value" list, and # when any key is repeated, we want to keep all its values in an array +: my %hash; while (<>) { my ( $k, $v ) = split; push @{$hash{$k}}, $v; } for my $k ( keys %hash ) { print "$k occurred ". scalar @{$hash{$k}} ." times\n"; }
    (update: but it seems like the OP really wants a hash-of-hashes, as suggested in the first reply above, rather than a hash-of-arrays.)