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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

To eliminate repeated of an array

Status
Not open for further replies.

mackiew

Programmer
Sep 15, 2000
18
0
0
UY
Exist some function to eliminate repeated elements of an Array ???

Example @array = ('a','b','a','x','x','b','c')

after function(\@array)

@array = ('a','b','x','c')

Thanks


 
I sometimes take a different approach to building the array...... Instead of using a simple list, I use a hash and as I get a new value I use it as a key who's value is '1'.

While (<INCOMING>) { $letters{$_} = 1; }

If any 'letter' repeats in <INCOMING>, it overwrites the previous instance in the hash
You can then, get your letters back with keys(%letters).

Or, you can use a variation on that trick against the array that you already have,

@array = ('a','b','a','x','x','b','c');

foreach $char (@array) { $letters{$char} = 1; }
@unique_chars = sort(keys(%letters));

'hope this helps....



keep the rudder amid ship and beware the odd typo
 
Here's a short subroutine I wrote to do it:

sub unique {

my(@list) = @_;

my %list = map { $_ => 1 } @list;

return sort keys %list;

} # unique

It takes an array (list) parameter and returns the same:

@nodupes = unique(@array);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top