Bri*_*ian 0 database string perl unique duplicates
这是我开始的地方.我使用while循环一次从数据库中读取数组.我想从数据库中获取重复的元素(在某些字段上).我想只保留这些字段中唯一的项目.然后我想以某种方式打印出我保存的数据.我创建了我认为会做的代码,但是它给了我一切,包括在场上重复的项目.我一直在搜索和搜索,我无法弄清楚,我在想,作为一个perl菜鸟,我想念一些简单的东西.代码如下:
my @uniques = ();
my $output;
while (my @itemArray = $sth->fetchrow_array() ) {
my $duplicateFlag = 0;
foreach (@uniques){
if( ($itemArray[3] eq "$_->[3]") and ($itemArray[4] eq "$_->[4]")
and ($itemArray[5] eq "$_->[5]" ) and ($itemArray[6] eq "$_->[6]" )
and ($itemArray[7] eq "$_->[7]" ) and ($itemArray[8] == "$_->[8]" ) ){
$duplicateFlag = 1;
}
}
if( $duplicateflag == 0){
$refToAdd = \@itemArray;
push(@uniques, $refToAdd);
$output .= "$itemArray[3]" . "\t$itemArray[8]" . "\t$itemArray[5]" . "\t$itemArray[7]\n";
}
}
print $output
Run Code Online (Sandbox Code Playgroud)
一种可能性:使用哈希来确定之前是否已经看过某个项目.从您的代码中简化一下:
my %dupHash;
while (my @itemArray = $sth->fetchrow_array() ) {
my $uniqueItem = itemArray[4];
if (not exists $dupHash{$uniqueItem}) {
print "Item $uniqueItem\n";
$dupHash{$uniqueItem} = \@itemArray;
}
}
Run Code Online (Sandbox Code Playgroud)
好的,它非常简单,但你明白了.通过使用我想要验证的值的散列是唯一的,我可以避免双循环和O 2算法效率.(Dang!大学那些年终于得到了回报!).
您可能希望通过组合要搜索重复的所有字段来使用更复杂的哈希键.也许是这样的:
# Probably could use join to make it more efficient...
my $uniqueKay = "$item[3]:$item[4]:$item[5]:$item[6]:$item[7]:$item[8]";
if (not exists $dupHash{$uniqueKey}) {
Run Code Online (Sandbox Code Playgroud)
如果你可以将它们存储在哈希中,那么最重要的是避免一次又一次地遍历所有唯一项.