Perl making an array unique

I had to write a Perl tool lately, which can make a list of things unique, like uniq(1) from GNU coreutils. In native Perl, there is no such function, to make an array only having unique values. So I came up with the idea using a hash for making an array unique very fast.

sub array_uniq
{
  my @array = @_;
  my %uniq = ();
 
  for (@array)
  {
    $uniq{$_} = undef; 
  }
 
  return(keys(%uniq));
}
 
my @uniq_array = array_uniq(@not_uniq_array);

I also checked, if there is a difference in performance using map instead of for, but it turned out, in this case, there isn't. After writing the code I had a look at Perl best practices and this way seems to be the most efficient.

Post new comment

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockcode>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options