Perl, convert hash to array

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

    If your original data source is a hash:

    # first find the max key value, if you don't already know it:
    use List::Util 'max';
    my $maxkey = max keys %hash;
    
    # get all the values, in order
    my @array = @hash{0 .. $maxkey};
    

    Or if your original data source is a hashref:

    my $maxkey = max keys %$hashref;
    my @array = @{$hashref}{0 .. $maxkey};
    

    This is easy to test using this example:

    my %hash;
    @hash{0 .. 9} = ('a' .. 'j');
    
    # insert code from above, and then print the result...
    use Data::Dumper;
    print Dumper(\%hash);
    print Dumper(\@array);
    
    $VAR1 = {
              '6' => 'g',
              '3' => 'd',
              '7' => 'h',
              '9' => 'j',
              '2' => 'c',
              '8' => 'i',
              '1' => 'b',
              '4' => 'e',
              '0' => 'a',
              '5' => 'f'
            };
    $VAR1 = [
              'a',
              'b',
              'c',
              'd',
              'e',
              'f',
              'g',
              'h',
              'i',
              'j'
            ];
    

提交回复
热议问题