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

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

     @hash{@array} = (1) x @array;
    

    It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.

    From the docs:

    If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

提交回复
热议问题