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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With