Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array > Push only unique records 1

Status
Not open for further replies.

Extension

Programmer
Nov 3, 2004
311
CA
Hi,

I would like to know if there's an easy way to push elements to an array only if they are unique. With my current code, I end up with some duplicates.

Reference.txt
Code:
TE|Value TE
TY|Value TY
RW|Value RW

Main.txt
Code:
ID0199|Record 0199|TE
ID2182|Record 2182|RW
ID4688|Record 4688|RW
ID4785|Record 4785|TY
ID7332|Record 7332|TE

Code:
# Open Main.txt
open(MAIN,"Main.txt") || die("Can't open file");
	
# Open Reference.txt
open(REFERENCE,"Reference.txt") || die("Could not open file!");					
@References = <REFERENCE>;
close(REFERENCE);
	
# Loop Around Main.txt
while ( my $Mains = <MAIN> ) {
	chomp $Mains;
      
	my @Main = split(/\|/,$Mains);
	
	# Loop Around Reference.txt
	foreach my $Ref (@References) {	
		chomp $Ref;
	
 		my @Reference = split(/\|/,$Ref);
						
		# Create New Array 
		if ($Reference[0] eq $Main[2]) {														
			push(@ReferencesExists,[@Reference]);

		}	
	}

}

return @ReferencesExists;

close(MAIN);
 
Code:
my %unique = ();

...

if (exists $unique{$Main[2]}) {
   # skip
   next;
}
else {
   $unique{$Main[2]} = 1;
}

push (@ReferenceExists,[@Reference]);

Another quick thing I noticed:
Code:
return @ReferencesExists;

close(MAIN);

MAIN won't be closed, because return is called before it. I don't think Perl will mind you leaving the filehandle open, but when you call return, the subroutine is stopped and execution goes back to the code that called it, so anything after a return isn't gonna be run.

-------------
Cuvou.com | The NEW Kirsle.net
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top