本文介绍了Perl中,转换哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在Perl中的哈希包含完整和连续的整数的映射(即从0到n的所有按键都被映射到的东西,没有这方面的外键),是否有此转换为数组的一种手段?
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.
推荐答案
如果您的原始数据源是一个哈希:
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};
或者,如果你原来的数据源是一个hashref:
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'
];
这篇关于Perl中,转换哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!