Perl, convert hash to array

2020-05-31 04:51发布

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.

标签: perl hash arrays
11条回答
Root(大扎)
2楼-- · 2020-05-31 05:38

You can extract all the values from a hash with the values function:

my @vals = values %hash;

If you want them in a particular order, then you can put the keys in the desired order and then take a hash slice from that:

my @sorted_vals = @hash{sort { $a <=> $b } keys %hash};
查看更多
疯言疯语
3楼-- · 2020-05-31 05:42
$Hash_value = 
{
'54' => 'abc',
'55' => 'def',
'56' => 'test',
};
while (my ($key,$value) = each %{$Hash_value})
{
 print "\n $key > $value";
}
查看更多
乱世女痞
4楼-- · 2020-05-31 05:52

Combining FM's and Ether's answers allows one to avoid defining an otherwise unnecessary scalar:

my @array = @hash{ 0 .. $#{[ keys %hash ]} };

The neat thing is that unlike with the scalar approach, $# works above even in the unlikely event that the default index of the first element, $[, is non-zero.

Of course, that would mean writing something silly and obfuscated like so:

my @array = @hash{ $[ .. $#{[ keys %hash ]} };   # Not recommended

But then there is always the remote chance that someone needs it somewhere (wince)...

查看更多
聊天终结者
5楼-- · 2020-05-31 05:53

We can write a while as below:

$j =0;
while(($a1,$b1)=each(%hash1)){
    $arr[$j][0] = $a1;
    ($arr[$j][1],$arr[$j][2],$arr[$j][3],$arr[$j][4],$arr[$j][5],$arr[$j][6]) = values($b1);
    $j++;
}

$a1 contains the key and $b1 contains the values In the above example i have Hash of array and the array contains 6 elements.

查看更多
forever°为你锁心
6楼-- · 2020-05-31 05:56

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'
        ];
查看更多
登录 后发表回答