Search code examples
perlhashperl-data-structures

How to print out complex hash without repeating the second level keys?


Hi I have a hash of hash containing class name, number of students enrolled and the names of student.
How do I print out this hash without repeating the second level keys.
Example: My data that I fill in my hash is Science Class, 3 students enrolled namely George,Lisa,Mathias and Math Class, 4 students enrolled Peter,George,Anna,Martin.

my %register=();

$register{$className}->{$count_students}=$student_name; # Fill the hash.

  foreach my $key ( keys %register ){      

   print "$key: ";

   foreach my $class ( keys %{ $register{$key} } ){

       print "$class=$register{$key}->{$class}\n";

   }  
}

I get result like:

Science_class: 2=Lisa
1=George
3=Mathias
Math_class: 2=Anna
1=Martin
3=Peter
4=George

But I want my result as:

Science_class: 3 -> Lisa, George, Mathias
Math_class: 4 -> Anna, Martin, Peter, George

How do I correct my script? Help me out.


Solution

  • You can get the number of entries in the second level with the keys function in scalar context, and you can get just the values in the second level with the values function.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my %register = (
        Science_class => {
            1 => "George",
            2 => "Lisa",
            3 => "Mathias",
        },
        Math_class => {
            1 => "Martin",
            2 => "Anna",
            3 => "Peter",
            4 => "George",
        }
    );
    
    for my $class (keys %register) {
        print "$class: ", scalar keys %{$register{$class}},
            " ", join(", ", values %{$register{$class}}), "\n";
    }
    

    However, given the structure of your data, a hash of arrayrefs makes more sense:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my %register = (
        Science_class => [
            "George",
            "Lisa",
            "Mathias",
        ],
        Math_class => [
            "Martin",
            "Anna",
            "Peter",
            "George",
        ]
    );
    
    for my $class (keys %register) {
        print "$class: ", scalar @{$register{$class}},
            " ", join(", ", @{$register{$class}}), "\n";
    }
    

    You may find reading perldoc perldsc useful in understanding how to create and manipulate data structures in Perl 5.