-1

I am new to programming and i am trying the c logic to implement in Perl for the array duplicate removal.

But i am not getting required output.Can some please give pointer where did i go wrong.

#!/usr/bin/perl -w

@x = (2,2,3,1);
$n = 3;
for ($i=0;$i<$n;$i++) {
    for ($j=$i+1;$j<$n;$j++) {
        if ($x[$i]=$x[$j]) {
            for ($k=$j;$k<$n;$k++)
            {
                print " pip";
                $x[$k] = $x[$k+1];
                print "k = $x[$k] ,j = $x[$j]\n";
                $n--;
            }
        } else {
            $j++;
        }
    }
}
print @x;
2
  • 1
    Please don't tag arbitrary languages that your question has nothing to do with. -Python. Commented Jun 20, 2014 at 12:24
  • 1
    if ($x[$i]=$x[$j]) { - Are you sure you want to assign here? Commented Jun 20, 2014 at 12:29

3 Answers 3

4

Your logic looks horrendous, but I do spot that you have made a rookie mistake, which may explain your program failing:

if ($x[$i] = $x[$j]) {

Here you are using the assignment operator = instead of the numerical equality operator ==. The assignment will, of course, assign the right hand parameter to the left hand parameter, which overwrites your array and corrupts your input.

As a side note, the return value of this statement is $x[$j], which may or may not be a true value, depending on your data. (for numerical data, 0 and undef will be false, all other true)

Edit:

It seems that this is not all that is wrong with your program, because it still fails. Trying to debug it does not seem like a good use of time, when deduping is so easily done in Perl, and this is a horrible way of doing it (sorry, but it is). Look at the other answers for how it is done with a hash -- make use of the fact that hash keys are unique.

This is how the dedupe function uniq is implemented in List::MoreUtils:

sub uniq (@) {
    my %seen = ();
    grep { not $seen{$_}++ } @_;
}

Quite simple, isn't it? Just return the keys which are not seen before.

Sign up to request clarification or add additional context in comments.

Comments

0

try using a hash for this:

my %h;
for my $i (@x) {
  $h{$i}++
}
@x = (keys %h);

this puts each value of @x into %h as the key and has the number of occurences of the element as the value in %h. if you just retrieve the keys (keys %h), you will have the distinct elements of @x, which you can then put back into @x.

Comments

0

it does not want to change the contents when you are referring to an element of an array is good.

@x = (2,2,3,1);
@hash { @x } = 0; 
@x = keys %hash;
print @x;

#use Array::Uniq from CPAN
use Array::Uniq;
@x = (2,2,3,1);
@x = uniq @x; #or uniq sort @x;
print @x; # result:231

1 Comment

Thanks all of you time for valuable feedback.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.