Perl, convert hash to array

后端 未结 11 2088
借酒劲吻你
借酒劲吻你 2021-02-05 06:56

If I have a hash in Perl that contains complete and sequential integer mappings (ie, all keys from from 0 to n are mapped to something, no keys outside of this), is there a mean

11条回答
  •  日久生厌
    2021-02-05 07:41

    This will leave keys not defined in %hashed_keys as undef:

    # if we're being nitpicky about when and how much memory
    # is allocated for the array (for run-time optimization):
    my @keys_arr = (undef) x scalar %hashed_keys;
    
    @keys_arr[(keys %hashed_keys)] =
        @hashed_keys{(keys %hashed_keys)};
    

    And, if you're using references:

    @{$keys_arr}[(keys %{$hashed_keys})] = 
        @{$hashed_keys}{(keys %{$hashed_keys})};
    

    Or, more dangerously, as it assumes what you said is true (it may not always be true … Just sayin'!):

    @keys_arr = @hashed_keys{(sort {$a <=> $b} keys %hashed_keys)};
    

    But this is sort of beside the point. If they were integer-indexed to begin with, why are they in a hash now?

提交回复
热议问题