Toby
Toby

Reputation: 3905

Perl nested foreach-loop with the same Hash

I have the following hash, which I fill with data I get from a file:

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

So the Hash looks like this (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
                          },

Now I want to write the data into a file. Which should look like this:

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

To access my hash I use this code:

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
    }
}

When I use the code like this, I get for the second foreach loop the following error:

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

and

Global symbol "$modulegrp" requires explicit package name

Actually I thought, my Hash is clean and this should work, so I have no idea what I am doing wrong. Maybe someone can help?

Upvotes: 0

Views: 221

Answers (1)

fugu
fugu

Reputation: 6578

You should sort as follows:

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

You don't need the quotes around the $a or $b

You have a hash of hashes, so you should dereference like so:

keys %{$hash{$key})

Upvotes: 1

Related Questions