I have a multidimensional array and I'm looking for a way to get only unique elements in the array.
use strict;
use feature 'say';
use List::Util 'shuffle';
#use List::MoreUtils 'uniq';
my @array = shuffle (
[4, 10],
[5, 6],
[1, 2],
[1, 2],
[1, 2]
);
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
};
my @unique = uniq(@array);
foreach (@unique) {say "@$_";};
And this doesn't work. It seems like each array in a multidimensional array is a different reference.
I tried to use uniq from MoreUtils but it also doesn't work.
Please help.
P/s: I'm looking for a way to produce [4, 10] [5, 6] [1, 2].
You have to reference both array values in your
%seenhash:Instead of a nested hash, you could stringify the two elements like so:
For the general case of an array of arbitrary data structures you can serialize the elements. This example uses
Storable::freezefor serialization.$Storable::canonicalneeds to be set to true to allow for comparison of data structures. See documentation. As @Ikegami points out, this will still cause problems with float values...