将数组推送到Perl中数组中的某个散列

时间:2015-09-02 23:36:45

标签: arrays perl push hash

我想在Perl中将哈希值动态推送到哈希数组中。

我有这个代码块来创建classHash并将其推送到数组classList。

    $courseName = <STDIN>;
    $section = <STDIN>;

    my $classHash = {};

    $classHash->{courseName} = $courseName;
    $classHash->{section} = $section;
    push @classList, $classHash;

现在,我想将一个studentHash添加到classHash。

    for my $i ( 0 .. $#classList ) {
        #I want to add the studentHash to a specific classHash in the classList
        if($courseName1 eq $classList[$i]{courseName} && $section1 eq $classList[$i]{section}){
             $studName = <STDIN>;
             $studNum = <STDIN>;

             my $studHash = {};

             $studHash->{studName} = $studName;
             $studHash->{studNum} = $studNum;

             push @studList, $studHash;
             push @{$classList[$i]}, \@studList; #but this creates an array reference error
        }
    }

1 个答案:

答案 0 :(得分:1)

忽略交互式位...以下是如何将学生添加到课堂中的内容:

#!/usr/bin/env perl

use warnings;
use strict;

use Data::Dumper;

my @classList = (
    {
       courseName => 'Algebra',
       section    => 101,
       students   => [],
    },
    {
       courseName => 'Geometry',
       section    => 102,
       students   => [],
    }, 
 );

my $studName = 'Alice';
my $studNum  = 13579;
my $desiredClass = 'Geometry';
my $desiredSection = 102;

for my $class (@classList) {
    if ($class->{courseName} eq $desiredClass and
        $class->{section}    eq $desiredSection) {
        # Add student to the class
        my $student = {
            studName => $studName,
            studNum  => $studNum,
        };
        push @{ $class->{students} }, $student;
    }
}

print Dumper \@classList;

# Printing out the students for each class
for my $class (@classList) {
    my $course  = $class->{courseName};
    my $section = $class->{courseSection};
    my $students = $class->{students};
    my $total_students = scalar @$students;
    my $names = join ', ', map { $_->{studName} } @$students;

    print "There are $total_students taking $course section $section.\n";
    print "There names are [ $names ]\n";
}

<强>输出

VAR1 = [
      {
        'students' => [],
        'section' => 101,
        'courseName' => 'Algebra'
      },
      {
        'students' => [
                        {
                          'studNum' => 13579,
                          'studName' => 'Alice'
                        }
                      ],
        'section' => 102,
        'courseName' => 'Geometry'
      }
    ];

There are 0 students taking Algebra section 101.
There names are [ ]
There are 1 students taking Geometry section 102.
There names are [ Alice ]