Perl使用相同的Hash嵌套foreach-loop

时间:2014-08-05 09:45:57

标签: perl hash foreach

我有以下哈希,我填写了从文件中获取的数据:

my %group_info;
# Read the file
# ...

$group_info{$modulegrp}{$id}{'Count'} = $msg_count;
$group_info{$modulegrp}{$id}{'ID'} = $id;
$group_info{$modulegrp}{$id}{'LINT Classification'} = $msgtype;
$group_info{$modulegrp}{$id}{'MISRA Classification'} = 'Required';

所以Hash看起来像这样(Datadump):

  # Modulegroup  # ID      # Data
      'So' => {
                '9004' => {
                            'ID' => '9004',
                            'MISRA Classification' => 'Required',
                            'LINT Classification' => 'Note',
                            'Count' => 156
                                                },
                '9034' => {
                            'ID' => '9034',
                            'MISRA Classification' => 'Required',
                            'LINT Classification' => 'Note',
                            'Count' => 107
                          }
      'Mt' => {
                '9004' => {
                            'ID' => '9004',
                            'MISRA Classification' => 'Required',
                            'LINT Classification' => 'Note',
                            'Count' => 159
                          },

现在我想将数据写入文件。这应该是这样的:

MODULEGROUP A
    ID | Count | Classifciation
    ID | Count | Classifciation
MODULEGROUP B
    ....

要访问我的哈希,我使用以下代码:

foreach my $modulegrp (sort {"\L$a" cmp "\L$b" }keys(%group_info))
{
    $current_line++;
    # Write Modulegroup
    print MYFILE $modulegrp
    foreach my $id (sort { "$a" <=> "$b" }keys($group_info{$modulegrp}))
    {
          # This doesn't work
    }
}

当我使用这样的代码时,我得到第二个foreach循环以下错误:

Syntax error at [...] line 182, near "$id (

Global symbol "$modulegrp" requires explicit package name

实际上我想,我的哈希很干净,这应该有效,所以我不知道我做错了什么。也许有人可以提供帮助?

1 个答案:

答案 0 :(得分:1)

您应按如下方式排序:

foreach my $var (sort { $a <=> $b } keys %{$hash{$key}) { # use cmp for non-numerics
...
}

您不需要$a$b

附近的引号

你有哈希哈希,所以你应该像这样取消引用:

keys %{$hash{$key})