Perl动态生成的多维关联数组

时间:2012-01-15 03:55:09

标签: perl multidimensional-array associative-array

这可能是我的一个简单的疏忽(或者比我的技能更先进的东西)。我试图通过读取文件中的输入来动态填充二维关联数组。

my @data;
while (<FILE>) {
    chomp;

    my $ID,$COUNT;
    print "READ: " . $_ . "\n"; #Debug 1

    ($ID,$COUNT,undef,undef,undef) = split /\,/;
    print "DATA: " . $ID . "," . $COUNT . "\n"; # Debug 2

    $data{$ID}{"count"} = $COUNT;
    #push @{$data{$ID}{"count"}}, $COUNT; 

              print $data{$ID}{"count"} . "\n"; # Debug 3
}

第一次打印(调试1)将打印类似于des313,3 ,,,。

的行

第二次打印(Debug 2)将打印一行DATA:des313,3

第三次打印(Debug 3)将打印一个空行。

这个问题似乎与我试图将数据插入关联数组的方式有关。我已尝试直接插入和推送方法没有结果。我用PHP完成了这个,但我想我在Perl中忽略了这一点。我确实看过HASHES HASHES部分中的perldoc perldsc页面但是我没有看到它谈论动态生成它们。任何建议都会很棒!

1 个答案:

答案 0 :(得分:5)

以你的方式分配哈希应该可以正常工作。您正在声明您的变量不正确。您的关联数组在Perl中称为哈希,并以% sigil为前缀,因此您应该在while循环之前编写my %data。在循环内部,my运算符需要将parens应用于列表,因此它应该是my ($ID, $COUNT);

这个最小的例子正常工作:

use warnings;  # place these lines at the top of all of your programs
use strict;    # they will catch many errors for you

my %data;  # hash variable
while (<DATA>) {
    chomp;
    my ($id, $count) = split /,/;  # simplify the split

    $data{$id}{count} = $count;    # build your hash
}

print "got: $data{des313}{count}\n";  # prints "got: 3"

__DATA__
des313,3
相关问题