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

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

    @hash{@keys} = undef;
    

    The syntax here where you are referring to the hash with an @ is a hash slice. We're basically saying $hash{$keys[0]} AND $hash{$keys[1]} AND $hash{$keys[2]} ... is a list on the left hand side of the =, an lvalue, and we're assigning to that list, which actually goes into the hash and sets the values for all the named keys. In this case, I only specified one value, so that value goes into $hash{$keys[0]}, and the other hash entries all auto-vivify (come to life) with undefined values. [My original suggestion here was set the expression = 1, which would've set that one key to 1 and the others to undef. I changed it for consistency, but as we'll see below, the exact values do not matter.]

    When you realize that the lvalue, the expression on the left hand side of the =, is a list built out of the hash, then it'll start to make some sense why we're using that @. [Except I think this will change in Perl 6.]

    The idea here is that you are using the hash as a set. What matters is not the value I am assigning; it's just the existence of the keys. So what you want to do is not something like:

    if ($hash{$key} == 1) # then key is in the hash
    

    instead:

    if (exists $hash{$key}) # then key is in the set
    

    It's actually more efficient to just run an exists check than to bother with the value in the hash, although to me the important thing here is just the concept that you are representing a set just with the keys of the hash. Also, somebody pointed out that by using undef as the value here, we will consume less storage space than we would assigning a value. (And also generate less confusion, as the value does not matter, and my solution would assign a value only to the first element in the hash and leave the others undef, and some other solutions are turning cartwheels to build an array of values to go into the hash; completely wasted effort).

提交回复
热议问题