Click to See Complete Forum and Search --> : pre-define a sort for a foreach loop


crmpicco
09-11-2008, 05:30 AM
I currently have this code that sorts an array based on the starttime, however, i'd like to pre-define the sort. Something like the code I have below, starting with stadium, then field, then park.... is this possible? If so, how can I achieve this?



foreach $item (sort { $a->{starttime} <=> $b->{starttime} } @{$place->{items}}) {

# $item->{type} is "stadium"

}



something like.....

foreach $item (sort { qw(stadium field park) } @{$covermorebooking->{items}}) {

Cheers,
Picco

Sixtease
09-12-2008, 12:47 AM
I'm not quite sure I get it. Do you want to sort by stadium, those with equal stadium by field and those with both equal by park?

Like if you had (discarding park)
@items = (
{ stadium => 1, field => 9 },
{ stadium => 1, field => 7 },
{ stadium => 2, field => 8 },
);
then you'd like to have them sorted
{ stadium => 1, field => 7 },
{ stadium => 1, field => 9 },
{ stadium => 2, field => 8 },

If that's the case, then you could do:
foreach $item (sort {
my $s_a = $a->{stadium};
my $s_b = $b->{stadium};
if ($s_a != $s_b) { $s_a <=> $s_b }
else { $a->{field} <=> $b->{field} }
} @items) { ... }
If you wish to factor out the fields by which you sort into an array, then I'd do it like this:
my @fields = qw/stadium field park/;
sub compare {
my ($A, $B) = @_;
foreach my $field (@fields) {
my $f_a = $A->{ $field };
my $f_b = $B->{ $field };
if ($f_a != $f_b) {
return $f_a <=> $f_b;
}
}
return 0;
}

foreach $item (sort { compare($a, $b) } @items) { ... }