如何将数组转换为Perl中的哈希? [英] How do I convert an array to a hash in Perl?

查看:126
本文介绍了如何将数组转换为Perl中的哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  open(FILE,message.xml)||死不能打开......; 

$ var =< FILE>;

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

$ i = 0;
$ num = @array; $($ $ $ $)
{
if(($ array [$ i] =〜/ ^ \ w + / i)||($ array [$ i] =〜/ \ d + /))
{
#printMatched \\\
;
#print\t $ array [$ i] \\\
;
push(@new,$ array [$ i]);
}
$ i ++;
}
打印@ new\\\
;


使用Tie :: IxHash;
tie%ha​​sh,Tie :: IxHash;

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

产生的输出是不正确的:

  name Protocol_discriminator属性强制类型半字节值7 min 0 max F name Security_header属性强制类型半字节值778 min 0X00 max 9940486857 
name => Security_header
属性=>强制性
type =>轻咬
值=> 778
分钟=> 0X00
max => 9940486857

在输出中,您可以看到散列仅由一部分构成,另一部分该数组没有在哈希中创建。



任何人都可以提供帮助吗?

解决方案
 %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;

这篇关于如何将数组转换为Perl中的哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆