我是Perl新手,我无法完全了解我的代码出了什么问题。我相信我正确使用语法,但我怀疑问题可能是这一行:这是为什么复制或覆盖列表的内容?
push @students, \%information;
我要的是对学生的名单包含的学生的信息哈希值。我期望的是,在每次添加学生后,都会创建学生信息的另一个散列并将其链接到列表的最新索引。但是,如果我同时输入了学生数据,最新的内容会覆盖前一个内容,因此当您打印它时,您会在上一个列表条目中看到最新输入信息的重复内容。如果我输入了1位学生并在添加后马上查看,然后输入了另一位学生,最新的学生将覆盖以前的学生。有人可以解释这一点吗?谢谢!
这是我的代码:
use strict;
use warnings;
my $userchoice = 0;
my $i;
my @students =(); #empty array
my %information =();
while ($userchoice != 4) {
print "------------------------------\n";
print "Welcome! What would you like to do?\n";
print "[0]Create Student Record\n";
print "[1]Edit Student Record\n";
print "[2]View Student Record\n";
print "[3]Delete Student Record\n";
print "[4]Exit\n";
print "Your Choice : ";
$userchoice = <STDIN>;
chomp($userchoice);
if ($userchoice == 0) {
print "-----------\n";
print "CREATE STUDENT RECORD.\n";
if ($#students <= 9) {
print "Name : ";
$information{"name"} = <STDIN>;
chomp($information{"name"});
push @students, \%information;
}
print "Student Record Full. " if ($#students >= 10);
}
if ($userchoice == 2) {
print "\nVIEW STUDENTS.\n";
print "[0]View One Student\n";
print "[1]View All Students\n";
print "[2]Back to Main Menu\n";
print "Your Choice : ";
$userchoice = <STDIN>;
if ($userchoice == 1) {
print "VIEW ALL STUDENTS.\n";
print "STUDENT 1---------------\n";
print "Name : ", $students[0]->{"name"}, " \n";
print "STUDENT 2---------------\n";
print "Name : ", $students[1]->{"name"}, " \n";
}
}
}
您需要每次使用引用到一个新的哈希值,而不是试图引用相同的哈希每一次。最简单的方法是在循环体内定义'%information'。 – 2014-09-04 16:43:59
要调试这样的问题,请在循环中使用'Data :: Dumper'。 – toolic 2014-09-04 16:50:27
明白了!感谢乔纳森。它真的被重复,因为列表的排序引用相同的散列...谢谢! – ejandra 2014-09-04 17:00:55