我正在尝试在perl中创建一个哈希数组,并且我在打印时遇到一些麻烦,因为唯一打印出来的是输入的最后一个哈希值。
我如何将哈希表推入数组中有什么问题吗?另外,如何正确打印数组的内容(哈希表)?
print "\n===========SUBJECTS===========\n";
my $exit = "n";
until ( $exit eq "y" ) { #loops until user enters 'y'
print "Course Number: ";
my $cNum = <STDIN>;
chomp($cNum);
print "Course Credit: ";
my $cCred = <STDIN>;
print "Grade: ";
my $cGrade = <STDIN>;
%subHash = (
"courseNumber" => $cNum,
"courseCredit" => $cCred,
"courseGrade" => $cGrade,
);
push @subList, \%subHash;
$subCount += 1;
print "\nFinished adding subjects?\n[y/n]\nCHOICE: "; #asks for subject input termination
$exit = <STDIN>;
chomp($exit);
print "\n==============================\n";
}
答案 0 :(得分:0)
您需要循环遍历散列引用数组,并相应地解除引用。
for my $hash_ref (@AoH)
{
for my $key (keys %{$hash_ref})
{
print "$key => $hash_ref->{$key}\n"
}
}
或
for my $hash_ref (@AoH)
{
while (my ($key, $val) = each %{$hash_ref})
{
print "$key => $val\n";
}
}
有关嵌套数据结构的更多信息,请参阅perldoc perldsc
,包括将其打印出来。
答案 1 :(得分:0)
答案已经给你了。您是否无法将其复制并粘贴到作业中?
use strict;
use warnings;
my @subList;
print "\n===========SUBJECTS===========\n";
my $exit = "n";
until ( $exit eq "y" ) { #loops until user enters 'y'
print "Course Number: ";
my $cNum = <STDIN>;
chomp($cNum);
print "Course Credit: ";
my $cCred = <STDIN>;
chomp($cCred);
print "Grade: ";
my $cGrade = <STDIN>;
chomp($cGrade);
push @subList, {
"courseNumber" => $cNum,
"courseCredit" => $cCred,
"courseGrade" => $cGrade,
};
print "\nFinished adding subjects?\n[y/n]\nCHOICE: "; #asks for subject input termination
$exit = <STDIN>;
chomp($exit);
print "\n==============================\n";
}
foreach my $hashref ( @subList ) {
while ( my ($key, $val) = each %{$hashref} ) {
print "$key => $val\n";
}
print "-----\n";
}