However if your code is not performance critical and you want to have a solution that is more in line with working with objects, you may prefer to create the following base class:
Now just inherit from that and define a useful 'cmp' method and you can sort in whatever order makes sense. For instance:package Sortable; use overload 'cmp' => \&_cmp; sub _cmp { $_[0]->cmp($_[1]); } 1;
allows you to make anonymous arrays that will compare with other anonymous arrays in a lexicographical sort.package AnonArray; # Quick demo of how Sortable works use Sortable; @ISA = ('Sortable'); sub cmp { my $self = shift; my $other = shift; my $len = @$self > @$other ? @$self : @$other; for (0..($len - 1)) { if (my $res = $self->[$_] cmp $other->[$_]) { return $res; } } if ($len < @$self) { return 1; } elsif ($len < @$other) { return -1; } else { return 0; } } sub new { my $class = shift; return bless [@_], $class; } 1;
UPDATE
For the record I don't have an opinion on whether the
overload approach is a good idea. It was something
I was playing with, and it was satisfying to see that
I could set up complex sorts using that idea.
But I just don't know if it is really worth it to design
a system that much at variance with how Perl works by
default. If anyone has a more concrete opinion, I would
be interested to hear it...
UPDATE 2
Sorry, I should have given an example of what it looks
like in action. Well suppose that you create an array
of AnonArrays and put it in @to_sort. Then you just try:
and the comparison function is picked up behind the scenes from Sortable. :-)@sorted = sort @to_sort;
In reply to Re (tilly) 1: OO and sorting
by tilly
in thread OO and sorting
by artist
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |