簡體   English   中英

如何在 Perl 中將數組轉換為散列?

[英]How do I convert an array to a hash in 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

在輸出中,您可以看到散列僅由一部分構成,而數組的另一部分並未在散列中創建。

任何人都可以幫忙嗎?

沒有比它更多:

%hash = @array;

在相關的說明中,將@array所有元素轉換為%hash鍵。 在這里結束的一些人可能真的想要這個......

這允許使用exists函數:

my %hash;
$hash{$_}++ for (@array);
my %hash = map {$_ => 1 } @array'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM