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

时间:2021-05-28 03:37:50

I have an array and tried to convert the array contents to a hash with keys and values. Index 0 is a key, index 1 is a value, index 2 is a key, index 3 is a value, etc.

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

But it is not producing the expected result. The code is below:

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

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";
}

The output produced is not correct:

产生的输出不正确:

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

In the output you can see that the hash is formed only with one part, and another part of the array is not getting created in the hash.

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

Can anyone help?

有人可以帮忙吗?

2 个解决方案

#1


37  

Nothing more to it than:

没有比它更多:

%hash = @array;

#2


25  

On a related note, to convert all elements of @array into keys of %hash. Some people ending up here might really want this instead...

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

This allows use of exists function:

这允许使用exists函数:

my %hash;
$hash{$_}++ for (@array);

#1


37  

Nothing more to it than:

没有比它更多:

%hash = @array;

#2


25  

On a related note, to convert all elements of @array into keys of %hash. Some people ending up here might really want this instead...

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

This allows use of exists function:

这允许使用exists函数:

my %hash;
$hash{$_}++ for (@array);