Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Showing Hash of Hashes

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;
<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>

{% embed include file="src/examples/dancer/show_hoh/planets.csv)

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();