in reply to Re^2: Removing duplicates in Array of Array
in thread Removing duplicates in Array of Array

Ah, so the bigger picture is that you need a deep copy of the elements from the original array? That is, at present you fall foul of:

use strict; use warnings; my %seen; my @array = (["1", "1", "3"], ["1", "5", "6"], ["1", "1", "3"]); my @unique = grep {! $seen{$_->[1]}++} @array; print "@$_\n" for @array; print "\n"; map {$_++} @$_ for @unique; print "@$_\n" for @array; print "\n";

Prints:

1 1 3 1 5 6 1 1 3 2 2 4 2 6 7 1 1 3

where you wanted @array unaffected by the manipulation of the contents of @unique. If you know that you are dealing with an AoA then you can:

use strict; use warnings; my %seen; my @array = (["1", "1", "3"], ["1", "5", "6"], ["1", "1", "3"]); my @unique = map {[@$_]} grep {! $seen{$_->[1]}++} @array; print "@$_\n" for @array; print "\n"; map {$_++} @$_ for @unique; print "@$_\n" for @array; print "\n"; print "@$_\n" for @unique; print "\n";

Prints:

1 1 3 1 5 6 1 1 3 1 1 3 1 5 6 1 1 3 2 2 4 2 6 7

Note the map used with the result from grep to copy the elements of each unique row? So actually rather than using neither grep nor map, what you really needed was to use both grep and map!


Perl reduces RSI - it saves typing

Replies are listed 'Best First'.
Re^4: Removing duplicates in Array of Array
by parv (Parson) on Sep 04, 2008 at 05:48 UTC

    ... or just the map (no golf; grep was excessive) ...

    my @unique = map { ! $seen{ $_->[1] }++ ? [ @{ $_ } ] : () } @array;

      In the general case that is quite true, but in the context of the OP using both was virtually required. ;)


      Perl reduces RSI - it saves typing
Re^4: Removing duplicates in Array of Array
by iphony (Acolyte) on Sep 04, 2008 at 06:02 UTC
    Hey GrandFather, thanks for your help. Using Map together with Grep does the trick. Thanks so much for your help. You are really the GrandFather of Perl...