Showing Hash of Hashes
examples/dancer/show_hoh/app.psgi
package App; use Dancer2; use Text::CSV; set 'template' => 'template_toolkit'; get '/' => sub { my %planets; my $filename = 'planets.csv'; open my $fh, '<', $filename or die; my $csv = Text::CSV->new ({ binary => 1, auto_diag => 1, }); my $header = $csv->getline($fh); $csv->column_names($header); while (my $row = $csv->getline_hr($fh)) { $row->{Distance} = delete $row->{"Distance (AU)"}; $planets{ $row->{"Planet name"} } = $row; } return template 'page', { planets => \%planets }; }; App->to_app;
examples/dancer/show_hoh/views/page.tt
<h1>Planets</h1> <table> <tr><th>Planet name</th><th>Distance (AU)</th><th>Mass</th></tr> [% FOR planet IN planets.keys.sort -%] <tr><td>[% planet %]</td><td>[% planets.$planet.Distance %]</td><td>[% planets.$planet.Mass %]</td></tr> [% END -%] </table> [% USE Dumper %] <pre> [% Dumper.dump(planets) %] </pre>
examples/dancer/show_hoh/planets.csv
Planet name,Distance (AU),Mass Mercury,0.4,0.055 Venus,0.7,0.815 Earth,1,1 Mars,1.5,0.107 Ceres,2.77,0.00015 Jupiter,5.2,318 Saturn,9.5,95 Uranus,19.6,14 Neptune,30,17 Pluto,39,0.00218 Charon,39,0.000254
examples/dancer/show_hoh/test.t
use strict; use warnings; use Test::More; use Plack::Test; use Plack::Util; use HTTP::Request::Common; my $app = Plack::Util::load_psgi './app.psgi'; my $test = Plack::Test->create($app); my $res = $test->request(GET '/'); is $res->status_line, '200 OK', 'Status'; like $res->content, qr{<h1>Planets</h1>}; like $res->content, qr{<td>Mercury</td>}; done_testing();