Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Remove repetitions in Array (http://www.go4expert.com/articles/remove-repetitions-array-t4059/)

oleber 28Apr2007 16:52

Remove repetitions in Array
 
The normal idea is to have an hash table, iterate over the array and using the elements as keys.

Something like ::(
Code: PERL

my @array = (1,5,3,7,9,1,4,5,7,6,7);

my %hash;

foreach my $element (@array) {
    $hash{$element}++
}

my @arrayNoRep = keys %hash;
print join(", ", @arrayNoRep);

Lets simplify the loop :cool:
Code: PERL

my @array = (1,5,3,7,9,1,4,5,7,6,7);

my %hash;
$hash{$_}++ foreach @array;

my @arrayNoRep = keys %hash;
print join(", ", @arrayNoRep);

But do we need the loop? :confused:
Code: PERL

my @array = (1,5,3,7,9,1,4,5,7,6,7);

my %hash;
@hash{@array} = ();

my @arrayNoRep = keys %hash;
print join(", ", @arrayNoRep);

And throwing away the hash defeniton. :eek:
Code: =PERL

my @array = (1,5,3,7,9,1,4,5,7,6,7);

my @arrayNoRep = keys %{{map {$_=>0} @array}};

print join(", ", @arrayNoRep);

I love this one line in Perl.:D

pradeep 30Apr2007 11:29

Re: Remove repetitions in Array
 
That's really cool! :D

oleber 4Jun2010 16:49

Re: Remove repetitions in Array
 
This post has become a Recipe at my new Perl website.

http://sites.google.com/site/oleberp...n-free-array-1

msmani_1980 26Jul2010 18:21

Re: Remove repetitions in Array
 
Remove repetitions in Array without loop

Code:

my @array = (1,5,3,7,9,1,4,5,7,6,7);
@t{@array}=();
print join sort keys %t,",";

Result : 1, 3, 4, 5, 6, 7, 9

oleber 26Jul2010 18:27

Re: Remove repetitions in Array
 
So, What did you add to the subject msmani_1980?

PradeepKr 13Sep2010 14:59

Re: Remove repetitions in Array
 
I couldn't get this line in the 3rd code block
@hash{@array} = ();

hash is defined with % in the previous line (%hash) and then it is seen with @ which is meant for array. Can somebody explain me, what exactly "@", prepended to hashname, does?

pradeep 13Sep2010 23:18

Re: Remove repetitions in Array
 
"@", prepended to hashname means we are accessing a hash slice i.e. a group of elements instead of one element a time.


All times are GMT +5.5. The time now is 05:57.