Last.fm API の結果を HTML::Template を使って出力する
Last.fmのAPIと「XML::Simple」 - ragutarouの日記の発展形。
Last.fm APIを使い、"ragtime"タグが多く付けられているアーティストを抜き出す。その結果(xml)を HTML::Template を使ってcgiで表示させる。
#!/usr/bin/perl -T use strict; use warnings; use CGI; use CGI::Carp qw(fatalsToBrowser); use LWP::Simple; use XML::Simple; use HTML::Template; my $tag = "ragtime"; my $url = "http://ws.audioscrobbler.com/1.0/tag/$tag/topartists.xml"; my $ls = LWP::Simple::get($url) or die $!; my $xs = XML::Simple->new; my $ref = $xs->XMLin($ls); my @data; for (keys %{$ref->{artist}}) { push @data, { ARTIST => $_, URL => $ref->{artist}->{$_}->{url}, COUNT => $ref->{artist}->{$_}->{count} }; } # Countで降順ソート my @sorted = sort { $b->{COUNT} <=> $a->{COUNT} } @data; ##__PRINT_HTML__ # header my $q = new CGI; print $q->header(-charset => 'utf-8'), $q->start_html('HTML::Template Test'); # template - loop my $tp = HTML::Template->new(filename => 'lastfm.tmpl'); $tp->param(ARTIST_INFO => \@sorted); print $tp->output;
■テンプレートファイル (lastfm.tmpl)
<table border=1> <TMPL_LOOP NAME=ARTIST_INFO> <tr> <td><TMPL_VAR NAME=ARTIST></td> <td><TMPL_VAR NAME=URL></td> <td><TMPL_VAR NAME=COUNT></td> </tr> </TMPL_LOOP> </table>
■出力結果
<title>HTML::Template Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <table border=1> <tr> <td>Scott Joplin</td> <td>http://www.last.fm/music/Scott+Joplin</td> <td>79</td> </tr> <tr> <td>The Ditty Bops</td> <td>http://www.last.fm/music/The+Ditty+Bops</td> <td>11</td> </tr> <tr> <td>Jelly Roll Morton</td> <td>http://www.last.fm/music/Jelly+Roll+Morton</td> <td>9</td> </tr> 〜以下、省略〜
ローカルのWebサーバで確認したところ、外部のAPIに問合せているとはいえ画面が表示されるまで4秒程度…おっそ!