如何在修改基础数据时保持指示对象的更改?

时间:2018-06-18 19:44:50

标签: perl

Script1

use strict;
use Data::Dumper;
use Getopt::Long qw(GetOptions);

my @results;
my @result1 = ('Chemisty', '87');
my @result2 = ('French', '80');

my $results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

#
push @results, \@result1;
$results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

#
push @results, \@result2;
$results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

SCRIPT2

use strict;
use Data::Dumper;
use Getopt::Long qw(GetOptions);

my @results;
my @result1 = ('Chemisty', '87');

my $results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

#
push @results, \@result1;
$results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

@result1 = ('French', '80');

#
push @results, \@result1;
$results_len = scalar @results;
print "============   results [$results_len] ==========================\n";
print Dumper(\@results);
print "==========================**\n";

在script2中...我应该如何清除result1,以便我可以重新使用它并获得类似于script1的输出?

我尝试使用undef,将其设置为空白...如果我再次使用“my result1”将其重置,则会显示警告

1 个答案:

答案 0 :(得分:1)

push @foo, \@bar将对命名数组@bar的引用添加到数组@foo。如果@bar的内容稍后更新,那么它也会影响@foo的内容。

当您预计@bar将会更新时,解决方法是将对@bar的当前副本的引用推送到@foo。这可以使用[ @bar ]语法来完成,该语法创建一个由@bar初始化的新数组引用。

@bar = ( ... );
push @foo, [ @bar ];
@bar = ( ... ); # something else
push @foo, [ @bar ];
...