Given an array of hashes, I want to use Template Toolkit to loop through the array sorted by a hash key 'name':

my @array = ( { name => 'foo', value => 1 }, { name => 'bar', value => 2 }, { name => 'baz', value => 3 } );
[% FOREACH element IN array.sort('name') %] [% element.name %] [% END %]

This works ok if @array has zero or more than 1 member.

However, if @array has exactly 1 member, the virtual method "sort()" will instead return the contents of that one hash in alphabetical order. Needless to say, this causes the output to be completely wrong since "element.name" will now render as a series of empty strings because they will be undefined.

Obviously, there is no need to sort an array with only one member, but in actual use I have no way of knowing in advance how many members there will be.

Does anyone know of a known fix/workaround for this problem? How can I tell Template that "array" is in fact an array?

Update:

I found a workaround that seems to do the trick:

[% PERL %] my $copy; @{$copy} = $stash->get('array'); if (ref($copy) eq 'ARRAY') { $stash->set('copy', sort { $a->{'name'} cmp $b->{'name'} } @{$copy}) +; } [% END %] [% FOREACH element IN copy %] [% element.name %] [% END %]
-- FloydATC

Time flies when you don't know what you're doing


In reply to Template, sorting an array with only one member by FloydATC

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.