From Sam Tregars' excellent perldoc HTML::Template documentation describing how to create a <TMPL_LOOP> referenced list:
my @words = qw(I Am Cool); my @numbers = qw(1 2 3); my @loop_data = (); # initialize an array to hold your loop while (@words and @numbers) { my %row_data; # get a fresh hash for the row data # fill in this row $row_data{WORD} = shift @words; $row_data{NUMBER} = shift @numbers; # the crucial step - push a reference to this row into the loop! push(@loop_data, \%row_data); } # finally, assign the loop data to the loop param, again with a ref $template->param(THIS_LOOP => \@loop_data);
All well and good, but is there a better or shorter, way to do it? Now, if you're extracting the data from a MySQL table everything can be simplified (via fetchrow_hashref) and by creating a sub (not necessary but useful if extracting data for several loops).
sub getLoopData { my $table = shift; my $order = shift; my @fields = @_; my $sql = "SELECT " . join (', ', @fields) . " from $table ORDER B +Y $order"; my $sth = $dbh->prepare_cached($sql); $sth->execute(); my @rows; while (my $row = $sth->fetchrow_hashref) { push (@rows, $row); } return \@rows; }
Which can be called by something like:
my $template->param(foo_loop => &getLoopData('foo', 'bar', 'baz', 'm +oo'));
Nice. MySQL's fetchrow_hashref function takes care of the referencing for you. I was wondering if theres a nice Perl (golfish) way of doing the same. Sams sample used two arrays, but, what if there was only one, heres a working example:
my @years = (); my @years_loop = (); my $curr_year = (localtime)[5]; $curr_year += 1900; for ($curr_year - 100 .. $curr_year - 5) { push (@years, $_); } while (@years) { my %year_data; $year_data{year} = shift @years; push (@years_loop, \%year_data); } $template->param(years_loop => \@years_loop);
Are all the steps within the while loop to get a referenced @years_loop array really necessary? ... well, they are necceasry in this instance otherwise it wouldn't work, but, as asked before, can anyone suggest a better, shorter (or even 'different', in the spirit of learning) way to do it?
This question is asked in the hope that I will get to understand Perl a little better. As can probably be extrapolated from this node I don't really know what I'm talking about so if anyone could throw me some pointers I'd be very grateful. (/me cowers in corner awaiting a thrashing ;)
In reply to A quesion about referencing lists by barrd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |