Below, I have modified your code which uses array indices and "looks forward" to the next element. I am sure you wondered why you needed to sort the array yet again? That is because the index of -1 means the last element of the array in Perl and that caused the largest value to appear at the beginning of the @unique array.
Here is another way of using "look ahead" indicies.... compare with your code...
I encourage you to sign up for a Perl Monk logon.use warnings; use strict; my @arr = (29,24,0,24,24,12,0,10,29,10,19,17,15,13,1,12,12,24,31); sub del_duplicate { my @sorted = sort{$a <=> $b} @_; my @unique; my $current; my $next; foreach my $index (0..@sorted-2) { $current = $sorted[$index]; $next = $sorted[++$index]; if ($current != $next) { push @unique, $current; } } # this is a "fix-it" statement after the loop # in order to get the last element of @sorted push @unique, $next; # add the last value print "@unique\n"; } del_duplicate(@arr); #0 1 10 12 13 15 17 19 24 29 31
Update: There is a problem with the above code if say, there is only a single element in @arr, i.e., @arr=(29);. This is one of several reasons why I would discourage iterating over array indices in Perl code.
In reply to Re: Trudging along the learning perl path.
by Marshall
in thread Trudging along the learning perl path.
by Anonymous Monk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |