gpt4 book ai didi

arrays - 为什么这会复制或覆盖列表的内容?

转载 作者:行者123 更新时间:2023-12-02 07:27:59 26 4
gpt4 key购买 nike

我是 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";
}
}
}

最佳答案

这总是将对同一散列的引用推送到数组 push @students,\%information;举例说明:

my %hash = ( index => 0 );
my @list = ();
foreach my $i (1..3) {
$hash{index} = $i;
push @list, \%hash;
}

for ( my $i=0; $i<@list; $i++ ) {
print "item $i - $list[$i] - $list[$i]->{index}\n";
}

从输出中注意到每个地址都是相同的:

item 0 - HASH(0x4c8068) - 3
item 1 - HASH(0x4c8068) - 3
item 2 - HASH(0x4c8068) - 3

您可以通过在循环内声明 %information 来修复

while($userchoice!=4){
my %information = ();

或者在推送时强制使用新的引用:

push @students, { %information };

关于arrays - 为什么这会复制或覆盖列表的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25670804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com