2014-04-21 58 views
0

我在寫一個子例程,它打印另一個數組中的非冗餘元素的數組。清空數組內循環,同時在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

由於方案範圍設置不正確,您正在重複使用之前通行證的@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

您可以嘗試uniqList::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 
相關問題