Hi, I'm trying to pickup CGI web application programming using Perl, DBI & TT (Template Toolkit). This small application is about storing data (using CGI::FormBuilder) list it using Template Toolkit. After retrieving records from MySQL using DBI, I've problem understanding how to pass to Template Toolkit, even though I've managed make it work by copy some code from Perl Mongers & Template Toolkit's tutorial. Below are my codes :
>>> start of list.cgi <<< #!/usr/bin/perl use warnings; use strict; #use diagnostics; use Template; use DBI; my %kar; my $tt_file='list.tt'; my $tt = Template->new({ INCLUDE_PATH => './tt', }) || die "$Template::ERROR\n"; my $vars = { kars => \%kar, }; sub db_select { my ($dsn,$dbuser,$dbpass,$dbh,$plh_reg_no,$sth,$reg_no,$brand,$cc); $dsn = "dbi:mysql:database=mycars:hostname=127.0.0.1"; $dbuser = "driver"; $dbpass = "plaintext"; $dbh = DBI->connect($dsn,$dbuser,$dbpass) or die "cannot connect to database : $DBI::errstr"; $plh_reg_no = "car%"; $sth = $dbh->prepare("SELECT reg_no,brand,CC FROM auto_details WHERE reg_no like ?"); $sth->execute($plh_reg_no) or die "Cannot execute statement : $DBI::errstr"; while (($reg_no, $brand, $cc) = $sth->fetchrow_array()) { $kar{$reg_no} = { reg_no => $reg_no, brand => $brand, cc => $cc } } $dbh->disconnect(); } db_select(); $tt->process($tt_file, $vars) || die "Template process failed: ", $tt->error(), "\n"; >>> end of list.cgi <<< >>> start of list.tt <<< Content-type: text/html [% PROCESS header %] Form <strong>List</strong> <p> <ul> [% FOREACH kar IN kars.values %] <li>[% kar.reg_no %], [% kar.brand %], [% kar.cc %]</li> [% END %] </ul> </p> [% PROCESS footer %] >>> end of list.tt <<< My question : - I suppose the above code convert array into hash and pass it to TT, is there any other way then this because I find that the line noise is a bit too much. - I've read about some where on some website that arrays passing to TT should always use array reference ($sth->fetchrow_arrayref) instead of the above, using arrays ($sth->fetchrow_array). If this were to use array reference, can someone show some codes to me so that i may check it out and try to understand. Thanks in advance, Edward.