【问题标题】:Perl nested foreach-loop with the same Hash具有相同哈希的 Perl 嵌套 foreach 循环
【发布时间】:2023-04-02 09:19:01
【问题描述】:

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

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';

所以哈希看起来像这样(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

实际上我认为,我的哈希是干净的,这应该可以工作,所以我不知道我做错了什么。也许有人可以帮忙?

【问题讨论】:

  • print 行之后foreach 之前也缺少一个分号。

标签: perl hash foreach


【解决方案1】:

你应该如下排序:

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

$a$b 周围不需要引号

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

keys %{$hash{$key})

【讨论】:

  • 哇,这很简单!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2023-04-11
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 2018-12-17
  • 2018-12-11
相关资源
最近更新 更多