Brett Sanger wrote:

So I have an array of hashrefs, that have date-related data (frex:
Month and year)

I've been asked to sort the output in most-recent-first order.

I tried: [% FOREACH Report = Reports.nsort('year').nsort('month') %]
(I expected this to be backwards, but I figured I'd mess with reverse
once I was sure this worked)


This didn't quite work as expected. I got the results I wanted with:

[% FOREACH Report = Reports.nsort('month').nsort('year').reverse %]

But I'm not sure that that's not just an artifact of my data.

The docs (Template::Manual::VMethods) don't seem to talk about
"stacking" vmethods...what is the expected order of resolution?  Does
the sort vmethod respect the previous order where there is no change
required?

If I understand what you are asking, you're probably better off sorting this in Perl before passing it along to the template, as you have a much greater flexibility with Perl's sort function.


---

# Sort descending by year, month.
@Reports = sort {
        $b->{year} <=> $a->{year} || $b->{month} <=> $a->{month}
} @Reports;

[ ... ]
$template->process("Report", { ... Reports => [EMAIL PROTECTED] ... });

---

And then your template is simplified:

[% FOREACH Report = Reports;
 ...
%]

It looks like what you have will work, but for complex datasets, especially when you have many pieces of data with different sort orders, you might end up getting confused. For example, if you also wanted to add a sort on "name" in ascending order:

---

# Sort descending by year, month; ascending by name.
@Reports = sort {
        $b->{year}  <=> $a->{year}    ||
        $b->{month} <=> $a->{month}   ||
        $a->{name}  cmp $b->{name}
} @Reports;
[ ... ]
$template->process("Report", { ... Reports => [EMAIL PROTECTED] ... });

---

Via template, you'd think this might work:

[% FOREACH Report = Reports.nsort('month').nsort('year').reverse.sort('Name') %]

But it wouldn't. You'd first sort the list by month, then year, then reverse it for most-recent-first order, but then the sort by Name would blow everything away.

---

Example:

[%
        a = [
                { year => 2003, month => 2, Name = "Schwarts, Randal" },
                { year => 2003, month => 2, Name = "Wardley, Andy" },
                { year => 2002, month => 4, Name = "Anderson, Jeff" },
                { year => 2003, month => 1, Name = "Nanor, Chris" }
        ];


FOREACH R = a.nsort('month').nsort('year').reverse.sort('Name'); "$R.year/$R.month -> $R.Name\n"; END; %]

Output:

2002/4 -> Anderson, Jeff
2003/1 -> Nanor, Chris
2003/2 -> Schwarts, Randal
2003/2 -> Wardley, Andy

---

So if you don't need to do anything further with the data you have, then you should be fine, if you need to get any more complex with the sort order, "use Perl;".

- Cliff
Self Proclaimed TT Addict

_______________________________________________
templates mailing list
[EMAIL PROTECTED]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to