In Perl, how do I create a hash whose keys come from a given array?

后端 未结 14 690
你的背包
你的背包 2021-01-29 19:53

Let\'s say I have an array, and I know I\'m going to be doing a lot of \"Does the array contain X?\" checks. The efficient way to do this is to turn that array into a hash, wher

相关标签:
14条回答
  • 2021-01-29 20:46

    You could also use Perl6::Junction.

    use Perl6::Junction qw'any';
    
    my @arr = ( 1, 2, 3 );
    
    if( any(@arr) == 1 ){ ... }
    
    0 讨论(0)
  • 2021-01-29 20:50
    %hash = map { $_ => 1 } @array;
    

    It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.

    What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.

    0 讨论(0)
提交回复
热议问题