且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-14 11:27:26

 %hash = @array; 


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?

Nothing more to it than:

%hash = @array;