in reply to Removing Duplicate Array Elements!!!

Thanks for all the help...problem solved!!! How do I rate responses?
  • Comment on Re: Removing Duplicate Array Elements!!!

Replies are listed 'Best First'.
Re^2: Removing Duplicate Array Elements!!!
by SridharKesari (Initiate) on Sep 24, 2015 at 11:35 UTC
    my @dup_array = qw\sridhar sridhar guru chan guru hubli hubli hubli hu +rryo\; my %unique_hash; foreach my $x (@dup_array) { $unique_hash{$x} = 1; } @dup_array = keys %unique_hash; print "\n\n\n@dup_array";
    Here is efficient way to remove dup elements in array, Every element is stored in a hash with key as the array element and value as 1. Since a hash cannot have duplicate keys, after populating the hash, the keys from the hash will consist of distinct array elements.

      Hello SridharKesari, and welcome to the Monastery!

      The hash method has one drawback: it doesn’t preserve the order in which the words first appear in the original array. Here’s a simpler approach that does:

      #! perl use strict; use warnings; use Data::Dump; use List::MoreUtils 'uniq'; dd uniq qw{ sridhar sridhar guru chan guru hubli hubli hubli hurryo };

      Output:

      22:48 >perl 1381_SoPW.pl ("sridhar", "guru", "chan", "hubli", "hurryo") 22:48 >

      And here’s the sorted equivalent:

      dd sort +uniq qw{ sridhar sridhar guru chan guru hubli hubli hubli hur +ryo };

      (The + is needed here to tell Perl that uniq supplies the values to be sorted, not the sort comparison routine. See the section beginning “Warning: syntactical care is required...” in sort.)

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      my @dup_array = qw\sridhar sridhar guru chan guru hubli hubli hubli hu +rryo\; my %unique_hash; foreach my $x (@dup_array) { $unique_hash{$x} = 1; } @dup_array = keys %unique_hash; print "\n\n\n@dup_array";

      Sridar, I love you as a fellow human being, but please use <code> </code> HTML tags around your code. You are killing me.

      I see choroba's note, but I can't help it.