Search code examples
perlhasharrays

Perl, convert numerically-keyed hash to array


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 means of converting this to an Array?

I know I could iterate over the key/value pairs and place them into a new array, but something tells me there should be a built-in means of doing this.


Solution

  • 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'
            ];