如何在 Perl 中将数组转换为散列?
我有一个数组,并尝试将数组内容转换为带有键和值的哈希值。索引 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
在输出中,您可以看到哈希仅由一部分组成,而数组的另一部分未在哈希中创建。
有人可以帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无非就是:
Nothing more to it than:
相关说明,将
@array
的所有元素转换为%hash
的键。有些人最终来到这里可能真的想要这个......这允许使用存在函数:
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: