Tie::Array::Sorted - An array which is kept sorted
use Tie::Array::Sorted; tie @a, "Tie::Array::Sorted", sub { $_[0] <=> $_[1] }; push @a, 10, 4, 7, 3, 4; print "@a"; # "3 4 4 7 10"
This presents an ordinary array, but is kept sorted. All pushes and unshifts cause the elements in question to be inserted in the appropriate location to maintain order.
Direct stores ($a[10] = "wibble") effectively splice out the original value and insert the new element. It's not clear why you'd want to use direct stores like that, but this module does the right thing if you do.
$a[10] = "wibble"
If you don't like the ordinary lexical comparator, you can provide your own; it should compare the two elements it is given. For instance, a numeric comparator would look like this:
tie @a, "Tie::Array::Sorted", sub { $_[0] <=> $_[1] }
Whereas to compare a list of files by their sizes, you'd so something like:
tie @a, "Tie::Array::Sorted", sub { -s $_[0] <=> -s $_[1] }
You may find, after profiling your code, that you do far more stores than fetches. In this case, doing a sorted insertion is inefficient, and you only need to sort on retrieval. You can turn on lazy sorting by tying to the Tie::Array::Sorted::Lazy subclass, which does the right thing. Naturally, it only re-sorts if data has been added since the last sort.
Tie::Array::Sorted::Lazy
tie @a, "Tie::Array::Sorted::Lazy", sub { -s $_[0] <=> -s $_[1] };
Simon Cozens, <simon@cpan.org>
Copyright 2003 by Kasei, 2004 by Simon Cozens
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Tie::Array::Sorted, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Tie::Array::Sorted
CPAN shell
perl -MCPAN -e shell install Tie::Array::Sorted
For more information on module installation, please visit the detailed CPAN module installation guide.