FreeKB - Remove duplicate values from an array in Perl
Remove duplicate values from an array in Perl

Home > Search


Let's say you have an array that has duplicate values.

@array = qw(one two one three one);

 

The following Perl script will remove the duplicates.

sub uniq {
  my %seen;
  grep not $seen{$_}++, @_;
}

@unique = uniq(@array);

 

Printing the @unique array will now produce the following.

one two three

 

Credit goes to Greg Hewgill at this Stack Overflow post.

 

Let's say you have a hash array that contains duplicate values.

push ( @{$hash{name}}, "Jeremy" );
push ( @{$hash{name}}, "Jeremy" );

 

The following will append the unique values to a new array (newhash).

my %seen;
my %newhash;

foreach my $key (keys %hash) {
  foreach my $value (@{$hash{$key}}) {

    if ( not $seen{$value}++) {
      print "$value has not been seen yet\n";
      push ( @{$newhash{name}}, "$value" );
    }
    else {
      print "$value has been seen\n";
    }
  }
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 17665 in the box below so that we can be sure you are a human.




Comments