in reply to Re: Remove Array Duplicates from Array of Arrays
in thread Remove Array Duplicates from Array of Arrays
my $key = join '', @$_;
Note that join-ing with the empty string means that, e.g., [ 'hello', 'sun and fun', 'day' ] cannot be distinguished from the arguably different subarray [ 'hello', 'sun and funday' ] (among other permutations):
A join string that is guaranteed not to appear in any text will avoid this. Here I use $; (see perlvar), the default value of which just happens to work in this particular case:c:\@Work\Perl\monks\Anonymous Monk>perl -wMstrict -le "use Data::Dump; ;; my @MyArrayOfArray = ( [ 'hello', 'sun and fun', 'day' ], [ 2, 'okay', 'may' ], [ 'hello', 'sun and funday' ], [ 2, 'okay', 'may' ], ); ;; my (%hash, @AoA2); ;; for (@MyArrayOfArray) { my $key = join '', @$_; push @AoA2, $_ unless exists $hash{ $key }; ++$hash{ $key }; } ;; dd \@AoA2; " [["hello", "sun and fun", "day"], [2, "okay", "may"]]
c:\@Work\Perl\monks\Anonymous Monk>perl -wMstrict -le "use Data::Dump; ;; my @MyArrayOfArray = ( [ 'hello', 'sun and fun', 'day' ], [ 2, 'okay', 'may' ], [ 'hello', 'sun and funday' ], [ 2, 'okay', 'may' ], ); ;; my (%hash, @AoA2); ;; for (@MyArrayOfArray) { my $key = join $;, @$_; push @AoA2, $_ unless exists $hash{ $key }; ++$hash{ $key }; } ;; dd \@AoA2; " [ ["hello", "sun and fun", "day"], [2, "okay", "may"], ["hello", "sun and funday"], ]
Update: Slightly more concisely:
(Update: Posted this update before I saw Dallaylaen's post with essentially the same idea.)c:\@Work\Perl\monks\Anonymous Monk>perl -wMstrict -le "use Data::Dump; ;; my @MyArrayOfArray = ( [ 'hello', 'sun and fun', 'day' ], [ 2, 'okay', 'may' ], [ 'hello', 'sun and funday' ], [ 2, 'okay', 'may' ], ); ;; my @AoA2 = do { my %seen; grep ! $seen{ join $;, @$_ }++, @MyArrayOfArray; }; ;; dd \@AoA2; " [ ["hello", "sun and fun", "day"], [2, "okay", "may"], ["hello", "sun and funday"], ]
Give a man a fish: <%-{-{-{-<
|
|---|