Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Monks, how are you!?

I am trying to compare and keep the unique values here and for each not equal element keep the greatest one. I can't figure it out, any help!
Here is how far I've got:
#!/usr/bin/perl use strict; use warnings; my $array_ref_x = [ [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '0', '0', '8' ], [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '3', '2', '0' ], ]; my %dual_ck = (); my $all_val; my @unique = (); foreach my $rows (@$array_ref_x){ next if $dual_ck{ $rows }++; push @unique, $rows; # trying here but did not work #my @unique = grep { ! $dual_ck{ $_ }++ } $rows; @$all_val = @unique; } print Dumper(@$all_val); #=cut # Here is what a happy end should be like ;-) =comment my $final_vals = [ [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '3', '2', '8' ], ]; =cut

Thanks for looking!

20090503 Janitored by Corion: Removed stray bold tag, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: Keeping Unique Elements in Array!
by almut (Canon) on May 01, 2009 at 17:55 UTC
    ...and for each not equal element keep the greatest one.

    So if I'm understanding correctly, you want to apply some kind of max() function on the corresponding row values.

    use strict; use warnings; use Data::Dumper; my $array_ref_x = [ [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '0', '0', '8' ], [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '3', '2', '0' ], ]; my $all_val = [ @{$array_ref_x->[0]} ]; my $i = 0; for my $row (@{$array_ref_x->[1]}) { $all_val->[$i] = $row if $row gt $all_val->[$i]; # assign greates +t $i++; } print Dumper $all_val; __END__ $VAR1 = [ 'ALICE WONDER', '9876543', '2009', '11.00', '711', '3', '2', '8' ];

    Use > instead of gt of your understanding of "greatest" is in the numeric sense.  Also, you could of course handle more than two arrays similarly by putting another loop around it...

      You are mentioning that if this is added to the array:
      [ 'ALICE WONDER', '9876543', '2009', '15.00', '711', '4', '5', '9' ],

      another loop has to be added to the code? What if you dont know the number of elements in this array?

        What I meant is something like this, in which case you can have any number of arrays with any number of rows:

        my $all_val = []; for my $aref (@$array_ref_x) { my $i = 0; for my $row (@$aref) { $all_val->[$i] = '' unless defined $all_val->[$i]; # for 'use + warnings' $all_val->[$i] = $row if $row gt $all_val->[$i]; $i++; } }