Re: deleting duplicates in array using references



On 30 Jul, 19:46, Paul Lalli <mri...@xxxxxxxxx> wrote:
On Jul 30, 2:37 pm, billb <billbea...@xxxxxxx> wrote:

i have a multidimensional array, but i want to delete duplicate
entries based on the first element of each 'row'.

$ perldoc -q duplicate
Found in /opt2/Perl5_8_4/lib/perl5/5.8.4/pod/perlfaq4.pod
How can I remove duplicate elements from a list or array?

my array is:

my @array = ( [UK9004411, A140, B, 0.040] , [UK0030239, H7140, H,
0.030] , [UK0030239, S1393, M1, 0.030] , [UK0012821, H4030, H,
0.010] , [UK0012821, H4060, H, 0.010] );

and I want to end up with
( [UK9004411, A140, B, 0.040] , [UK0030239, H7140, H, 0.030] ,
[UK0012821, H4030, H, 0.010] )

(no real preference in which row is dropped...just on a first come
first served basis.)

i.e. take out the duplicate codes based on the first element of each
row $array[$row] -> [0]

$ perl -MData::Dumper -e'
my @array = (
[UK9004411, A140, B, 0.040] ,
[UK0030239, H7140, H, 0.030] ,
[UK0030239, S1393, M1, 0.030] ,
[UK0012821, H4030, H, 0.010] ,
[UK0012821, H4060, H, 0.010] ,
);
my %seen;
my @nodups = grep { !$seen{$_->[0]}++ } @array;
print Dumper(\@nodups);
'
$VAR1 = [
[
'UK9004411',
'A140',
'B',
'0.04'
],
[
'UK0030239',
'H7140',
'H',
'0.03'
],
[
'UK0012821',
'H4030',
'H',
'0.01'
]
];

i looked into splice() function based on the index but not sure this
is the best way or the syntax for this?

splice (@array , $row, 1); ?

splice() is fine for removing the elements once you know which ones
you want to remove, but it's useless for actually finding which
elements to remove.

Paul Lalli

ah, very simple and very fast as well! I'll have to understand how
this is working. It uses a hash I see. Many thanks.

.



Relevant Pages

  • Re: writing get_script()
    ... "How can I remove duplicate elements from a list or array?" ... of a hash will automatically eliminate all duplicates. ... it is implemented using hash tables, but Joe Programmer normally doesn't ...
    (comp.lang.perl.misc)
  • Re: is there a compiler warning for this piece of code ?
    ... Thanks for your thoughts - I think your speculation as to the history of the ... An element of a char array cannot be NULL; ... > _address_ of the first element. ... >> Incorrect. ...
    (microsoft.public.vc.language)
  • Re: Fast lookup of ranges
    ... I have a peculiar (atleast to me) problem before my hand. ... big table with numeric ranges in each row. ... and the first element is always less than ... Chose an array length N, the larger the faster we can search. ...
    (comp.programming)
  • Re: writing get_script()
    ... to the highest index. ... remove the first element from an array. ... print "$verse $script\n"; ...
    (comp.lang.perl.misc)
  • Re: Invisible Array Loop Counter?
    ... What we see here is that in the first method, the first element you tried ... and the third element became a reference ... from the array. ...
    (comp.lang.perl.misc)