| Collections documentation | Contained in the Collections distribution. |
Collections::Sorted - Easy to use iterator with sorted elements
Version 0.01
use Collections::Sorted;
# Ordered collection
my $col = Collections::Sorted->new( sub { $_[0] <=> $_[1] } );
$col->add(101);
$col->add(102);
# this will return 101
print $col->first;
Sort blocks are expected to return -1, 0, 1 as default sort blocks on perl if your block only return two values that can cause bad sorted sets
Returns a new instace of a sorted Collection, first argument passed is the sort block, if no argument passed it will use default sort block which is sub { $_[0] <=> $_[1] }
my $collection = Collections::Sorted->new;
Read Collections::Ordered
Read Collections::Ordered
reverse method doesn't make sense for sorted collections, because order is imposed, so it will return an ordered collection with elements in reverse order
If passed with $sub changes the current sort block, it also re-sort the entire collection, if no arguments passed it returns the sort block
$colection->sort_block( sub { $_[0] <=> $_[1] });
Returns an Collections::Ordered with the same elements of this collection
my $col = $collection->to_ordered;
Mariano Wahlmann, <dichoso at gmail.com>
Please report any bugs or feature requests to dichoso at gmail.com.
I will be notified, and then you'll be notified of progress on your bug as I
make changes.
Copyright 2009 Mariano Wahlmann, all rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Collections documentation | Contained in the Collections distribution. |
package Collections::Sorted; use strict; use warnings; use base qw(Collections::Ordered);
sub new { my $class = shift; my $self = $class->SUPER::new(); $self->_initialize(@_); return $self; }
sub add { my $self = shift; $self->{is_dirty} = 1; return $self->SUPER::add(@_); }
sub add_all { my $self = shift; $self->{is_dirty} = 1; return $self->SUPER::add_all(@_); }
sub reverse { my $self = shift; return Collections::Ordered->from_array($self->to_array); }
sub sort_block { my $self = shift; if (@_) { $self->{sort_block} = shift; $self->{is_dirty} = 1; } return $self->{sort_block}; }
sub to_ordered { my $self = shift; my $new = Collections::Ordered->new; $new->add_all($self); return $new; } #- Private ---------------------------------------------------------------------- sub _elements { my $self = shift; # Sort before we do any operation with the elements if ( scalar($self->{elements}) > 1 and $self->{is_dirty} ) { $self->_sort; $self->{is_dirty} = undef; } return $self->{elements}; } sub _initialize { my $self = shift; $self->{is_dirty} = 1; if (@_) { $self->{sort_block} = shift; } else { $self->{sort_block} = sub { $_[0] <=> $_[1] }; } } sub _sort { my $self = shift; my $sort_block = $self->{sort_block}; $self->{elements} = [ sort { $sort_block->($a, $b) } @{ $self->{elements} } ]; } 1; __END__