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;
}