Wednesday, September 16, 2009

Perl: concise way to map one array onto antother in perl hash

Suppose I have two arrays. Suppose further elements in one of this array logically map onto elements of the other.


my @ar1 = (...);
my @ar2 = (...);


Easy way to map ar1 (keys) onto ar2 in perl is:


my %hash;
@hash{@ar1} = (@ar2) x @ar1;


Important assumption: the order in this two arrays matters. In other words first element of ar1 maps to first element of ar2, ..., n-th element of first array ar1 maps onto n-th element of ar2 and there exactly n elements in both arrays.


Examples

It is OK to have unique keys, obviously for the hash to preserve correct mapping (include use Data::Dumper in your code):


sub unique_mapping
{
my @ar1 = ('a', 'b', 'c', 'd', 'e');
my @ar2 = ('1', '2', '3', '4', '5');

print Dumper(\@ar1);
print Dumper(\@ar2);

my %hash;
@hash{@ar1} = (@ar2) x @ar1;


print Dumper(\%hash);

}


Result:


$VAR1 = [
'a',
'b',
'c',
'd',
'e'
];
$VAR1 = [
'1',
'2',
'3',
'4',
'5'
];
$VAR1 = {
'e' => '5',
'c' => '3',
'a' => '1',
'b' => '2',
'd' => '4'
};


The mapping is not what you might want to have in the case when keys are not unique:


sub keys_non_unique_mapping
{
my @ar1 = ('a', 'b', 'b', 'd', 'e');
my @ar2 = ('1', '2', '3', '4', '5');

print Dumper(\@ar1);
print Dumper(\@ar2);

my %hash;
@hash{@ar1} = (@ar2) x @ar1;


print Dumper(\%hash);

}


Result:


$VAR1 = [
'a',
'b',
'b',
'd',
'e'
];
$VAR1 = [
'1',
'2',
'3',
'4',
'5'
];
$VAR1 = {
'e' => '5',
'a' => '1',
'b' => '3',
'd' => '4'
};

No comments: