in reply to Howto Dynamically Create a Hash?

my @nlist = (3,24,8,17,23,14,17,9,16,24,25,11,22,14,14,8,19,16,15,8); my @key_list = ('A'..'Z'); my @lookup; my %hash; NLIST: foreach my $num (@nlist) { foreach (@lookup) { my ($factor, $key) = @$_; if ($num % $factor == 0) { push(@{$hash{$key}}, $num); next NLIST; } } my $key = shift(@key_list); push(@lookup, [$num, $key]); $hash{$key} = [ $num ]; } require Data::Dumper; print(Data::Dumper::Dumper(\%hash));

output: (reformatted for readability)

$VAR1 = { 'A' => [3,24,9,24,15], 'B' => [8,16,8,16,8], 'C' => [17,17], 'D' => [23], 'E' => [14,14,14], 'F' => [25], 'G' => [11,22], 'H' => [19] };

Replies are listed 'Best First'.
Re^2: Howto Dynamically Create a Hash?
by ikegami (Patriarch) on Oct 09, 2005 at 21:17 UTC

    Just a note about my code design:

    I didn't need to use a seperate lookup structure. I could just have interated over the keys of %hash (like Aristotle did). However, iterating over an array will return consistent results whereas iterating over a hash will not.

    Given
    @nlist = (9,3,27);
    always gives
    'A' => [9,27], 'B' => [3]
    with my code, but can give either
    'A' => [9,27], 'B' => [3]
    or
    'A' => [9], 'B' => [3,27]
    (unpredicatbly) when iterating through %hash.

      Did you read my code? I don’t iterate over any hash anywhere. Your claim that my code may produce inconsistent results is false.

      You stuck to the OP’s approach of shifting from the @key_list, which makes it unduly complicated to achieve consistency. I did not, so my code is simpler, but it is just as consistent.

      Makeshifts last the longest.

        Sorry, I added "(like Aristotle did)" via update after I saw your post. I guess i must have read it too quickly. My apologies.