magica has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I need to use an index value to access array elements in Template::Toolkit. I was not able to find any documentation on such syntax. Is this possible with Template::Toolkit. I have a few arrays. My goal is to loop over and access/print out the: 0th elements of all arrays first, then the 1st elements,....etc. Thanks much!
  • Comment on Random access of array elements in Template::Toolkit

Replies are listed 'Best First'.
Re: Random access of array elements in Template::Toolkit
by pc88mxer (Vicar) on Mar 04, 2008 at 01:37 UTC
    Try this (untested):
    [% FOREACH n IN [0 .. array1.size ] %] first array: [% array1.$n %] second array: [% array2.$n %] [% END %]

    This combines string interpolation with array accessing using the .N operator (e.g. array.0, array.1, etc.)

    You might have to interpolate ${array1.size} - that's why I say it's untested.

Re: Random access of array elements in Template::Toolkit
by kyle (Abbot) on Mar 04, 2008 at 03:08 UTC

    I think pc88mxer's answer is correct (though I haven't tested it either). The relevant section of the documentation is here.

      Awesome! That totally works:) Thanks monks!