如何使用来自数组表的键创建哈希表?
我有这个数组:my @array = ("car","bus","bike")
;
我需要像这样的哈希:
my %h = ( "car" => "1",
"bus" => "2",
"bike" => "3" );
感谢
答案 0 :(得分:1)
您可以使用哈希切片用键/值填充它,
my @array = ("car","bus","bike");
my %h;
@h{@array} = 1 .. @array;
答案 1 :(得分:0)
迭代数组的索引。
my %h;
for (0..$#array) {
$h{ $array[$_] } = $_ + 1;
}
可以缩短为
my %h = map { $array[$_] => $_+1 } 0..$#array;