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.

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


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

  1. my %hash;  
  2. @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):

  1. sub unique_mapping  
  2. {  
  3.  my @ar1 = ('a''b''c''d''e');  
  4.  my @ar2 = ('1''2''3''4''5');  
  5.    
  6.  print Dumper(\@ar1);  
  7.  print Dumper(\@ar2);  
  8.    
  9.  my %hash;  
  10.  @hash{@ar1} = (@ar2) x @ar1;  
  11.    
  12.    
  13.  print Dumper(\%hash);  
  14.    
  15. }  


Result:

  1. $VAR1 = [  
  2.           'a',  
  3.           'b',  
  4.           'c',  
  5.           'd',  
  6.           'e'  
  7.         ];  
  8. $VAR1 = [  
  9.           '1',  
  10.           '2',  
  11.           '3',  
  12.           '4',  
  13.           '5'  
  14.         ];  
  15. $VAR1 = {  
  16.           'e' => '5',  
  17.           'c' => '3',  
  18.           'a' => '1',  
  19.           'b' => '2',  
  20.           'd' => '4'  
  21.         };  


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

  1. sub keys_non_unique_mapping  
  2. {  
  3.  my @ar1 = ('a''b''b''d''e');  
  4.  my @ar2 = ('1''2''3''4''5');  
  5.    
  6.  print Dumper(\@ar1);  
  7.  print Dumper(\@ar2);  
  8.    
  9.  my %hash;  
  10.  @hash{@ar1} = (@ar2) x @ar1;  
  11.    
  12.    
  13.  print Dumper(\%hash);  
  14.    
  15. }  


Result:

  1. $VAR1 = [  
  2.           'a',  
  3.           'b',  
  4.           'b',  
  5.           'd',  
  6.           'e'  
  7.         ];  
  8. $VAR1 = [  
  9.           '1',  
  10.           '2',  
  11.           '3',  
  12.           '4',  
  13.           '5'  
  14.         ];  
  15. $VAR1 = {  
  16.           'e' => '5',  
  17.           'a' => '1',  
  18.           'b' => '3',  
  19.           'd' => '4'  
  20.         };  

No comments: