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

后端 未结 14 707
你的背包
你的背包 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-29 20:31

    You can place the code into a subroutine, if you don't want pollute your namespace.

    my $hash_ref =
      sub{
        my %hash;
        @hash{ @{[ qw'one two three' ]} } = undef;
        return \%hash;
      }->();
    

    Or even better:

    sub keylist(@){
      my %hash;
      @hash{@_} = undef;
      return \%hash;
    }
    
    my $hash_ref = keylist qw'one two three';
    
    # or
    
    my @key_list = qw'one two three';
    my $hash_ref = keylist @key_list;
    

    If you really wanted to pass an array reference:

    sub keylist(\@){
      my %hash;
      @hash{ @{$_[0]} } = undef if @_;
      return \%hash;
    }
    
    my @key_list = qw'one two three';
    my $hash_ref = keylist @key_list;
    

提交回复
热议问题