Reputation: 469
I'm trying to 'push' a list of key/value pairs into a perl hash as follows. I thought it would work like the key-value pairs are assigned when an array is assigned to a hash. @targets
contains tab separated strings for each elements. However for every iteration of the map loop, the hash is overwitten and at the end I only got one key-value pair in the hash which corresponds to the last element of the @targets
. I'm trying to avoid the usual $ID_Gene{$key}=$value
type assignments.
How to push a list as a key-value pair to the hash?
Alternatively, is there any way I can build an anonymous hash and then push that hash to the original hash?Like: %ID_Gene = (%ID_Gene, %AnonyHash);
my %ID_Gene;
map{ %ID_Gene= (split /\t/,$_) ;
}@targets;
Upvotes: 1
Views: 1301
Reputation: 240473
You're almost there, you just have the assignment in the wrong place, so you end up blowing away the entire hash each time you add an item. As a general rule, it usually doesn't make sense to do things with side-effects in map
. You can simply do:
my %ID_Gene = map { split /\t/, $_ } @targets;
if you already have some stuff in %ID_Gene
and you want to add to it, you can do
%ID_Gene = (%ID_Gene, map { split /\t/, $_ } @targets);
or if you think that's too much going on in one line:
my %to_add = map { split /\t/, $_ } @targets;
%ID_Gene = (%ID_Gene, %to_add);
Upvotes: 4