Loop through multidimensional Hash of Arrays in Perl -
i have multidimensional hash of arrays represent student's grade in each subject first 4 assignments.
my %students_grades = ( colton => { english => [ 90, 95, 80, 75 ], mathematics => [ 77, 89,94, 100 ], }, ); the syntax bit off here's code creates hash of arrays above.
#!/usr/bin/perl %students_grades; $students_grades{'colton'}{'english'}[0] = 90; $students_grades{'colton'}{'english'}[1] = 95; $students_grades{'colton'}{'english'}[2] = 80; $students_grades{'colton'}{'english'}[3] = 75; $students_grades{'colton'}{'history'}[0] = 77; $students_grades{'colton'}{'history'}[1] = 89; $students_grades{'colton'}{'history'}[2] = 94; $students_grades{'colton'}{'history'}[3] = 100; how loop through student's grades received in history using foreach loop? right i'm looping through using loop.
my $num_of_grades = scalar @{$students_grades{'colton'}{'history'}}; (my $i=0; $i <= $num_of_grades; $i++) { print $students_grades{'colton'}{'history'}[$i] . "\n"; } this representation of code in actual program hash of arrays more complicated want loop through hash of arrays using foreach loop because it'll easier handle. how do that?
for (my $i=0; $i<@array; ++$i) { $ele = $array[$i]; ... } can written simpler as
for $ele (@array) { ... } so have used following:
for $grade (@{ $students_grades{'colton'}{'english'} }) { print("$grade\n"); } my $grade = $students_grades{'colton'}{'english'}[0]; is short for
my $grade = $students_grades{'colton'}->{'english'}->[0]; which means can do
my $grades = $students_grades{'colton'}{'english'}; $grade = $grades->[0]; which means have used following:
my $grades = $students_grades{'colton'}{'english'}; $grade (@$grades) { print("$grade\n"); } knowing allows 1 escalate following:
for $student_name (keys(%students_grades)) { $student_grades_by_class = $students_grades{$student_name}; $class_name (keys(%$student_grades_by_class)) { $grades = $student_grades_by_class->{$class_name}; $grade (@$grades) { print("$student_name: $class_name: $grade\n"); } } }
Comments
Post a Comment