英文:
debug Perl loop to store data to a reference array
问题
以下是您提供的代码的翻译部分:
我有一段像这样的代码
foreach my $l(@inarray){
chop($l);
if($flag == 0 && $l =~ /^start /){
my @array01 = split(/\(/,$l);
$module_name = $array01[0];
my @array03 = split(/\s/,$array01[-1]);
$local_data{"module_name"} = $module_name;
$local_data{"variables"} = \@array03;
$flag = 1;
}
if($flag == 1 && $l =~ /input/){
chop($l);
$l =~ s/input\s+//g;
my @array01 = split(/,\s/,$l);
$local_data->{"input"} = \@array01;
}
if($flag == 1 && $l =~ /output/){
chop($l);
$l =~ s/output\s+//g;
my @array01 = split(/,\s/,$l);
$local_data->{"output"} = \@array01;
}
if($flag == 1 && $l =~ /end/){
push @$infos, $local_data;
$flag = 0;
}
}
但是,当我打印@$infos数组时,我看到数组的所有元素都与最后一个元素相同,它们应该是不同的,因为我正在使用标志来分隔它们。我不确定为什么会发生这种情况。
英文:
I have a piece of code like this
foreach my $l(@inarray){
chop($l);
if($flag == 0 && $l =~ /^start /){
my @array01 = split(/\(/,$l);
$module_name = $array01[0];
my @array03 = split(/\s/,$array01[-1]);
$local_data{"module_name"} = $module_name;
$local_data{"variables"} = \@array03;
$flag = 1;
}
if($flag == 1 && $l =~ /input/){
chop($l);
$l =~ s/input\s+//g;
my @array01 = split(/,\s/,$l);
$local_data->{"input"} = \@array01;
}
if($flag == 1 && $l =~ /output/){
chop($l);
$l =~ s/output\s+//g;
my @array01 = split(/,\s/,$l);
$local_data->{"output"} = \@array01;
}
if($flag == 1 && $l =~ /end/){
push @$infos, $local_data;
$flag = 0;
}
}
but when I print the @$infos array I saw all the elements of the array are the same as the last element, they are supposed to be different because I'm using the flag to separate them. I'm not sure why this is happening.
答案1
得分: 3
这段代码中只有一个(全局的)$local_data
,所以相同的对象一直被添加到@$infos
中。我认为你希望每次遇到end
标记时重置$local_data
。
push @$infos, $local_data;
$local_data = {}; # 或者 $local_data = LocalDataThing->new()
或者你可以每次都轻松添加$local_data
的(浅)拷贝。
push @$infos, {%$local_data};
英文:
There is only one (global) $local_data
in this code, so the same object keeps getting appended to @$infos
. I think you want to reset $local_data
each time you encounter the end
token.
push @$infos, $local_data;
$local_data = {}; # or $local_data = LocalDataThing->new()
Or you could easily append a (shallow) copy of $local_data
each time.
push @$infos, {%$local_data};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论