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

后端 未结 14 710
你的背包
你的背包 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:30

    Raldi's solution can be tightened up to this (the '=>' from the original is not necessary):

    my %hash = map { $_,1 } @array;
    

    This technique can also be used for turning text lists into hashes:

    my %hash = map { $_,1 } split(",",$line)
    

    Additionally if you have a line of values like this: "foo=1,bar=2,baz=3" you can do this:

    my %hash = map { split("=",$_) } split(",",$line);
    

    [EDIT to include]


    Another solution offered (which takes two lines) is:

    my %hash;
    #The values in %hash can only be accessed by doing exists($hash{$key})
    #The assignment only works with '= undef;' and will not work properly with '= 1;'
    #if you do '= 1;' only the hash key of $array[0] will be set to 1;
    @hash{@array} = undef;
    

提交回复
热议问题