Eliminating Duplicates using Grep

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Eliminating Duplicates using Grep

Smruti Mohanty
#!/usr/bin/perl -w
use strict;

my @list = qw(bob sally Andromalius sally bob ned Andromalius);


my @arr = ();

foreach(@list){    

    while (!grep(/$_/,@arr)) {
    push @arr, $_ ;
 
    }
   
}

print "@arr";


This only prints bob ... Please help!
Reply | Threaded
Open this post in threaded view
|

Re: Eliminating Duplicates using Grep

Guru
Administrator
This post was updated on .
foreach my $x(@list){
    if (!grep(/$x/,@arr)) {
    push @arr, $x ;
    }
}
print "@arr";


1. You should use if, not while.
2. Do not use $_ when using grep. Always use a collecting variable in the foreach. This is because $_ is used by grep.  As you know, grep  takes each element in the array, stores it in $_ and does the operation specified. So, never use $_ while using grep because grep uses it.

The above grep command  actually means this:

if (!grep($_ =~ /$x/,@arr))

  Now, imagine putting $_ in place of $x, thats why Perl does not understand it. Hope it helps.
Reply | Threaded
Open this post in threaded view
|

Re: Eliminating Duplicates using Grep

Smruti Mohanty
Thanks it worked.

Now

foreach my $x(@list){    
   
    while (!grep{$x}@arr){
    push @arr,$x ;
    }
   
}

Why this doesnot work?
Reply | Threaded
Open this post in threaded view
|

Re: Eliminating Duplicates using Grep

Guru
Administrator
' If' becomes successful if the condition is true. 'while' loop will keep on executing till the condition is true. While is used when i want to do something continuously, whereas in this case, you want to do it only once if true.

Second: grep {$x}@arr  This will be true always because $x always has a value. Keep in mind:

grep {$x} @arr  remains as is.

grep {/$x/}@arr means grep{$_ =~ /$x/}@arr

This is so because:

if (/abc/)   is same as  if ($_ =~m/abc/)