如何将数组转换为Perl中的哈希?

时间:2010-08-05 05:36:25

标签: perl hashmap

我有一个数组,并尝试将数组内容转换为带有键和值的哈希。索引0是键,索引1是键,索引2是键,索引3是值等。

但它没有产生预期的结果。代码如下:

open (FILE, "message.xml") || die "Cannot open\n";

$var = <FILE>;

while ($var ne "")
{
 chomp ($var);
 @temp = split (/[\s\t]\s*/,$var);
 push(@array,@temp);
 $var = <FILE>;
}

$i = 0;
$num = @array;
    while ($i < $num)
{
 if (($array[$i] =~ /^\w+/i) || ($array[$i] =~ /\d+/))
 {
#   print "Matched\n";
#   print "\t$array[$i]\n";
  push (@new, $array[$i]);
 }
 $i ++;
}
print "@new\n";


use Tie::IxHash;
tie %hash, "Tie::IxHash";

%hash = map {split ' ', $_, 2} @new;

while ((my $k, my $v) = each %hash)
{
 print "\t $k => $v\n";
}

产生的输出不正确:

name Protocol_discriminator attribute Mandatory type nibble value 7 min 0 max F name Security_header attribute Mandatory type nibble value 778 min 0X00 max 9940486857
         name => Security_header
         attribute => Mandatory
         type => nibble
         value => 778
         min => 0X00
         max => 9940486857

在输出中,您可以看到散列仅由一个部分组成,而数组的另一部分未在散列中创建。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:39)

没有比它更多的了:

%hash = @array;

答案 1 :(得分:27)

在相关说明中,将@array的所有元素转换为%hash的键。在这里结束的一些人可能真的想要这个......

这允许使用exists函数:

my %hash;
$hash{$_}++ for (@array);
相关问题