I'm trying to create an unique array regardless of its original order and using no module, this's what I've come up with so far:
my @arr = qw(b a a c d g e f);
my %hash;
@hash{@arr}=();
say keys %hash;
Yes. Since hash keys are unique, this is one idiomatic way to do it. The number of ways to accomplish the same thing are many.
You may also use a module, such as List::MoreUtils
use strict;
use warnings;
use List::MoreUtils qw(uniq);
print join ":", uniq qw(a a a b b c d);
Output:
a:b:c:d
Some different ways to dedupe:
my @arr = keys { map { $_ => 1 } qw(b a a c d g e f) };
The curly braces creates an anonymous hash for keys
, the map statement creates a list of key/value pairs.
my @arr = dedupe(qw(a a b c d d e));
sub dedupe {
my %hash = map { $_ => 1 } @_;
return keys %hash;
}
Same thing, but in subroutine form, and split into two lines. Note that both lists will be in a semi-random order, since hashes are unordered.
The subroutine used by List::MoreUtils
is equally simple, and perhaps preferable, since it will preserve the order of arguments. It still uses a hash, though.
sub uniq {
my %seen = ();
grep { not $seen{$_}++ } @_;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With