Reputation: 758
I need to order the @list
array by insertDate
, but how can I access it since it is a $obj
array?
I tried Perl's sort
function but I don't understand how it works with this kind of array composed of $obj
.
sub getLastQuestions {
my ($page) = @_;
$page ||= 1;
my $questionPerPage = 30;
my @list = [];
my @questions = $db->findNodes("/db/questions/question");
if (@questions) {
foreach my $question (@questions) {
my $id = $question->findvalue("\@id");
my $title = $question->findvalue("title");
my $author = $question->findvalue("author");
my $insertDate = $question->findvalue("insertDate");
my $obj = Model::Question->new(
path => "vedi-domanda.cgi?id=" . $id,
title => $title,
author => $author,
insertDate => $insertDate
);
# Aggiungi uno
push @list, $obj;
}
}
return @list;
}
Upvotes: 0
Views: 1622
Reputation: 126742
Note that there is no need for
if (@questions) { ... }
because
foreach my $question (@questions) { ... }
will not execute if the array is empty
There is also a bug in your initialisation of @list
, which you are setting to []
. This doesn't empty the array - it sets it to have one element which contains a reference to an empty array. Just my @list
is correct.
The easiest way to do this is to sort the @questions
array before transforming it into an array of Model::Question
objects.
The exact code depends entirely on the format of the date strings in the XML, but if they are well-formed, like an ISO 8601 date, then they can just be sorted as strings to get the desired effect. So you could write
my @questions = sort {
my ($aa, $bb) = map $_->findvalue('insertDate'), ($a, $b);
$aa cmp $bb;
} $db->findNodes('/db/questions/question');
Please note that you haven't shown the format of your date strings, so this may not work without some additional coding
You may also want to use map
to convert the XML nodes into Model::Question
objects, as I show in this subroutine
sub get_last_questions {
my ($page) = @_;
$page ||= 1;
my $_PerPage = 30;
my @questions = sort {
my ($aa, $bb) = map $_->findvalue('insertDate'), ($a, $b);
$aa cmp $bb;
} $db->findNodes('/db/questions/question');
my @list = map {
Model::Question->new(
path => 'vedi-domanda.cgi?id=' . $_->findvalue('@id'),
title => $_->findvalue('title'),
author => $_->findvalue('author'),
insertDate => $_->findvalue('insertDate'),
);
} @questions;
return @list;
}
Upvotes: 2