Perl, convert hash to array

后端 未结 11 2079
借酒劲吻你
借酒劲吻你 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:35

    OK, this is not very "built in" but works. It's also IMHO preferrable to any solution involving "sort" as it's faster.

    map { $array[$_] = $hash{$_} } keys %hash; # Or use foreach instead of map
    

    Otherwise, less efficient:

    my @array = map { $hash{$_} } sort { $a<=>$b } keys %hash;
    
    0 讨论(0)
  • 2021-02-05 07:38
    $Hash_value = 
    {
    '54' => 'abc',
    '55' => 'def',
    '56' => 'test',
    };
    while (my ($key,$value) = each %{$Hash_value})
    {
     print "\n $key > $value";
    }
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-02-05 07:42

    As DVK said, there is no built in way, but this will do the trick:

    my @array = map {$hash{$_}} sort {$a <=> $b} keys %hash;
    

    or this:

    my @array;
    
    keys %hash;
    
    while (my ($k, $v) = each %hash) {
        $array[$k] = $v
    }
    

    benchmark to see which is faster, my guess would be the second.

    0 讨论(0)
  • 2021-02-05 07:48

    Perl does not provide a built-in to solve your problem.

    If you know that the keys cover a particular range 0..N, you can leverage that fact:

    my $n = keys(%hash) - 1;
    my @keys_and_values = map { $_ => $hash{$_} } 0 .. $n;
    my @just_values     = @hash{0 .. $n};
    
    0 讨论(0)
提交回复
热议问题