Assuming you dont have undefined values or references as the values of @arr you can do this:
use Data::Dumper; %fruits=(); @arr = ([1,1],[1,2],[3,5],[6,7]); for (@arr) { my ($k,$v)=@$_; if (ref $fruits{$k}) { push @{$fruits{$k}},$v; } else{ $v=[$fruits{$k},$v] if (defined $fruits{$k}); $fruits{$k}=$v; } } print Dumper(\%fruits); __END__ $VAR1 = { '6' => 7, '1' => [ 1, 2 ], '3' => 5 };
Which is IMO a pattern perl programmers should be familiar with as it comes up fairly often. When only a few values will be lists the overhead of forcing each one to be an array can be unacceptable, but a hybrid works reasonably well. Imo generating stringified lists is not too desirable, but thats just me being a generalist, I suspect it could be a reasonable approach for some problems.
In reply to Re: How to store this value in Hash ?
by demerphq
in thread How to store this value in Hash ?
by gube
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |