Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push duplicate element of an array to a new array perl

Tags:

perl

Can anybody tell me how to push a duplicate element of an array to a new array? This is what I have till now, again I want to retain the duplicate elements into a new array.

%seen = ();
@uniq = ();
foreach $item (@list) {
    unless ($seen{$item}) {
        $seen{$item} = 1;
        push(@uniq, $item);
    }
}
print "@unique\n";
like image 560
Pink Avatar asked Nov 17 '25 20:11

Pink


1 Answers

Always start your scripts with use strict; and use warnings;.

use strict ;
use warnings ;

my @list = ( 1 .. 10 , 2 , 5 , 6 ) ;

my %seen = ();
foreach my $item (@list) {
  $seen{$item}++ ;
}

my @uniq = grep { $seen{$_} == 1 } keys %seen ;
my @not_unique = grep { $seen{$_} > 1 } keys %seen ;

Simply count each occurrence of the elements in a hash and use a grep afterwards.

like image 160
dgw Avatar answered Nov 19 '25 09:11

dgw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!