Tie::Array::Unique - Keep array's contents unique


  use Tie::Array::Unique;

  tie my(@array), 'Tie::Array::Unique';

  tie my(@array), 'Tie::Array::Unique',
    ("this", "this", "that");

  tie my(@array), 'Tie::Array::Unique',
    Tie::Array::Unique::How->new(sub { lc }),
    ("This", "this", "that");


This modules ensures the elements of an array will always be unique. You can provide a function defining how to determine uniqueness.


This is a very simple module. Use it as shown above, and your array will never have a duplicate element in it.

The earliest (i.e. lowest-indexed) element has precedence, as shown in this code sample:

  tie my(@x), 'Tie::Array::Unique';
  @x = (1, 2, 3, 4, 2, 5);  # (1, 2, 3, 4, 5)
  $x[1] = 5;                # (1, 5, 3, 4)
  $x[2] = 1;                # (1, 5, 4)

That last line causes $x[2] to be 1, but then the array is collapsed, which results in $x[2] getting removed.

Determining uniqueness

You can provide a wrapper function that converts each element before checking for uniqueness. It will not alter the actual values in the array, it only determines what happens to the value before it is checked for uniqueness.

A simple example is a case-insensitive array:

  tie my(@x), 'Tie::Array::Unique',
    Tie::Array::Unique::How->new(sub { lc shift });
  @x = qw( The man said to the boy );
  # (The, man, said, to, boy)
  $x[1] = 'BOY';
  # (The, BOY, said, to)


Gabor Szabo has written Array::Unique, which is similar.


Jeff japhy Pinyan, <>


Copyright (C) 2004 by japhy

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.3 or, at your option, any later version of Perl 5 you may have available.