Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Is this a correct way of creating an unique array?

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;
like image 992
bolbol Avatar asked Jan 16 '23 07:01

bolbol


1 Answers

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{$_}++ } @_;
}
like image 103
TLP Avatar answered Jan 29 '23 03:01

TLP