Perl: Is this the right way to create a unique array?

I am trying to create a unique array regardless of its original order and without using a module, this is what I have come up with so far:

my @arr = qw(baacdgef); my %hash; @hash{@arr}=(); say keys %hash; 
+4
source share
3 answers

Yes. Since hash keys are unique, this is one idiomatic way to do this. The number of ways to do the same thing is many.

You can also use a module, for example List :: MoreUtils

 use strict; use warnings; use List::MoreUtils qw(uniq); print join ":", uniq qw(aaabbcd); 

Conclusion:

 a:b:c:d 

Some methods of deduplication:

 my @arr = keys { map { $_ => 1 } qw(baacdgef) }; 

An anonymous hash for the keys is created in braces, the map operator creates a list of key / value pairs.


 my @arr = dedupe(qw(aabcdde)); sub dedupe { my %hash = map { $_ => 1 } @_; return keys %hash; } 

The same, but in the form of a subroutine and is divided into two lines. Please note that both lists will be in a random order, since the hashes are unordered.

The routine used by List::MoreUtils is equally simple and perhaps preferable, as it preserves the order of the arguments. However, it still uses a hash.

 sub uniq { my %seen = (); grep { not $seen{$_}++ } @_; } 
+6
source

Yes, you are using the right path, but there are many other ways to create a unique array.

see perlfaq4: How can I remove duplicate elements from a list or array? for more details.

+2
source

A unique array without ordering the aka set I know that you said "no module" (why ?!). But if you change your mind, try Set::Object or Set::Scalar

+1
source

All Articles