Two ways off the top of my head:
or ...# method 1 - always use an array: while (my @values = fetchrow_array()){ my $hash = ($values[0] => [ $values[1] ]); push (@{$hash{$values[0]}}, values[2]) }
I use the latter in more general cases where I want to default to a single scalar for most cases, and only fall back to arrays when I get the duplication. But the first one makes more sense in the code snippet you gave.# method 2 - switch scalars to arrays dynamically (good for other # cases, not so good for yours, here for completeness only) # rather than a simple push: if (exists $hash{$values[0]}) { if (not ref $hash{$values[0]} or ref $hash{$values[0]} ne 'ARRAY') { $hash{$values[0]} = [ $hash{$values[0]} ]; } push @{$hash{$values[0]}}, $hash{$values[2]};
Update: Off-by-everything error in the inner if in method 2, noted by jdalbec. Replaced "eq" with "ne". (Off-by-everything errors are more common for me than off-by-one errors :->)
In reply to Re: 2 elements referenced by one Key
by Tanktalus
in thread 2 elements referenced by one Key
by mnlight
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |