How do I convert an array to a hash in Perl?

╄→гoц情女王★ 提交于 2020-01-31 06:59:13

问题


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.

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?


回答1:


Nothing more to it than:

%hash = @array;



回答2:


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

This allows use of exists function:

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


来源:https://stackoverflow.com/questions/3412014/how-do-i-convert-an-array-to-a-hash-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!