in reply to Re: Removing Duplicate Array Elements!!!
in thread Removing Duplicate Array Elements!!!

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.

Replies are listed 'Best First'.
Re^3: Removing Duplicate Array Elements!!!
by Athanasius (Archbishop) on Sep 24, 2015 at 12:57 UTC

    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,

Re^3: Removing Duplicate Array Elements!!!
by Anonymous Monk on Sep 24, 2015 at 12:25 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";

    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.