Explanation
One array holds a set of keys. The values to these keys are inner hashes. The keys of these inner hashes, in this case are numbers (like array indices). Another array holds the values of the inner hash.
Question:
How can you populate the outer hash keys with the correct corresponding values (ie. correct inner hash)?
Contraints
I'd prefer a solution utilizing slices, map or grep. Eliminating cascading for loops
I realize it should be an HoA. But this is only for me to learn, it has no functional value...
Working Code:
This code works as I want but I would like to use more advanced techniques:
#! usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %register=();
my @classNames = ('Science_class', 'Math_class');
my @Science_class_student_names = ('George', 'Lisa', 'Mathias'); #prob from file
my @开发者_JAVA技巧Math_class_student_names = ('Martin', 'Anna', 'Peter', 'George'); #prob from file
foreach my $className (@classNames) {
my $array_name = $className.'_'.'student_names';
if ($array_name =~ /Science/) {
foreach (0..$#Science_class_student_names ) {
$register{$className}{$_ + 1} = $Science_class_student_names[$_];
}
}
elsif ($array_name =~ /Math/) {
foreach (0..$#Math_class_student_names ) {
$register{$className}{$_ + 1} = $Math_class_student_names[$_];
}
}
}
print Dumper(\%register);
Ideas
A hash slice works for direct key-value pairs, but the intermediate keys are throwing me off. Trying something like: @register{@classNames} = map{$count => $student}
One idea I had, before the if statements was if there was a way to use a string in the name of an array: $#($array_name)student_names
but that doesn't work.
Another would be to separately create an array of all the inner hash keys, use a slice and then put that hash into the outer hash.
The only other idea I had was using an AoA to hold all the 'inner hash value' arrays. (ie. my @studentNames = (\@Science_class_student_names, \@Math_class_student_names);
but haven't gotten anywhere with that yet.
It's easier to work on it a layer at a time. For the inner layer, it seems you want
1 => George,
2 => Lisa,
...
So start by figuring out how to do that.
map { $_+1 => $Science_class_student_names[$_] }
0..$#Science_class_student_names
So you end up with
$register{'Science_class'} = {
map { $_+1 => $Science_class_student_names[$_] }
0..$#Science_class_student_names
}
};
$register{'Math_class'} = {
map { $_+1 => $Math_class_student_names[$_] }
0..$#Math_class_student_names
}
};
If you generalise the inner layer, you get
for (
[ 'Science_class' => \@Science_class_student_names ],
[ 'Math_class' => \@Math_class_student_names ],
) {
my ($class_name, $student_names) = @$_;
$register{$class_name} = {
map { $_+1 => $student_names->[$_] }
0..$#$student_names
};
}
精彩评论