在PERL中使用push时清空循环内的数组

时间:2014-04-21 14:08:02

标签: arrays perl

我正在编写一个子程序,用于打印另一个数组中的非冗余元素数组。

此代码在我的子程序中。

foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";                           

然后我在我的主程序中的一个循环中调用我的子程序,第一次迭代就可以了,我的新表包含一次我的旧表。 但在此之后@new_table保留了过去迭代的元素,并且打印结果为false。

我尝试在我的子程序中清空@new_table,就像这样

@new_table = ();
foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";       

但是,除了第一个迭代之外,我的@new_table在所有迭代中都变为空。

这有什么问题,如何解决?

2 个答案:

答案 0 :(得分:2)

由于范围不正确,您需要重复使用先前传递的@new_table%seen。在循环之前创建它们。

my @new_table;
my %seen;
foreach (@old_table) { push(@new_table, $_) unless ($seen{$_}++); }
print "@new_table" . "\n";

这可以简化为

my %seen;
my @new_table = grep { !$seen{$_}++ } @old_table;
print "@new_table\n";

您也可以使用

use List::MoreUtils qw( uniq );

my @new_table = uniq(@old_table);
print "@new_table\n";

您正在使用use strict; use warnings;,对吧?如果不是,你应该是。总是

答案 1 :(得分:1)

您可以尝试uniq List::MoreUtils删除多余的元素。

my @new_table = uniq(@old_table);

引用perldoc

  

uniq LIST
  不同的LIST

     

通过在LIST中删除重复值来返回新列表。返回列表中元素的顺序与LIST中的相同。在   标量上下文,返回              LIST中唯一元素的数量。

           my @x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 1 2 3 5 4
           my $x = uniq 1, 1, 2, 2, 3, 5, 3, 4; # returns 5