我正在编写一个脚本,用于分析文件并希望将整个结果存储在数组中。我跑成我归结于以下代码中的问题:将Perl数组放入散列表
use strict;
use warnings;
use Data::Dumper;
my @sections =();
my @sections1 = qw/sect1 sect2 sect3/;
my @sections2 = qw/sect4 sect5/;
my @textbooks =();
my $text1 = { title => "title1", author => "author1" };
my $text2 = { title => "title2", author => "author2" };
for (@sections1) {
push(@sections, $_);
}
$text1->{sections} = \@sections;
@sections =();
for (@sections2) {
push(@sections, $_);
}
push(@textbooks, $text1);
$text2->{sections} = \@sections;
print Dumper($text2);
push(@textbooks, $text2);
print Dumper(@textbooks);
第一打印自卸车的结果如下:
$VAR1 = {
'title' => 'title2',
'sections' => [
'sect4',
'sect5'
],
'author' => 'author2'
}
,第二个的结果为:
$VAR1 = {
'sections' => [
'sect4',
'sect5'
],
'title' => 'title1',
'author' => 'author1'
};
$VAR2 = {
'title' => 'title2',
'sections' => $VAR1->{'sections'},
'author' => 'author2'
};
我对此有两个问题,我确信它们是相关的。
我意识到第一部分是一个引用,以便它们包含我期望的第二部分。我认为行
@sections=()
会创建一个新的数组,并在稍后进行新的引用。显然我没有正确地想到这一点。第二部分是怎么回事?从
$text2
的输出看来,它正确无误,直到推送。
使用'@sections = [];'正是我所需要的。谢谢。 –