Saturday, July 9, 2011

How to copy keys from hash to array without duplicates​?

#Method 1:

You could make use of List::MoreUtils's uniq function:

use List::MoreUtils qw( uniq );

@a = uniq @a, keys %h;


#Method 2:
Convert the values you want into hash keys, then extract them

my %foo = map { $_ => 1  } @a, keys %h;
print sort keys %foo;


Method 3:
If you have Perl 5.10 and later, you can use smart matching (~~):

for my $key (keys %h) {
   push @a, $key unless $key ~~ @a;
}

No comments: