CPAN からPerlモジュールインストールして使ってみましょう。CPANとはPerl用の様々なモジュールを管理しているサイトです。
以下の手順は、Linux、BSD、Mac OS X、Strawberry Perlで共通です。
ここでは「HTML::CalendarMonthSimple」という、カレンダーを作成するモジュールを使ったサンプルコードを示します。
まずは事前に作成しておいたコマンドプロンプト(記事3の最後に作り方が書いてます)を起動し、以下のようにタイプします。
perl -MCPAN -e shell
cpan> とプロンプトが表示され、CPANモードになったら、
cpan> install HTML::CalendarMonthSimple
と入力します。ズラズラとコンパイルしている様子が流れますが、あまり気にせず眺めておいてください。モジュールのインストールは1度限りでOKです。以後は普通に使えます。モジュールをインストールせずにサンプルソースを実行すると、「そのようなモジュールは存在しない」旨のエラーが英語で表示されます。
Strawberry Perlの素晴らしい点は、CPANコンパイルに必要な環境が自動で整備される点にあります。
CPANにはさまざまなモジュールが存在します。色々試してみましょう。
サンプルソース「mk_calendar.pl」
#!/usr/bin/perl
# コマンドプロンプトでCPANからモジュールをInstallする
# perl -MCPAN -e shell
# cpan>install HTML::CalendarMonthSimple
#perl5.8以降で日本語を扱う場合、必ずソースをUTF-8で記載すること。
use strict;
use warnings;
use Encode;
use utf8;
use HTML::CalendarMonthSimple; #←これが今回利用するCPANモジュール
binmode STDIN, ":encoding(cp932)"; # 入力なのに、何故かencoding
binmode STDOUT, ":encoding(cp932)";
binmode STDERR, ":encoding(cp932)";
# ファイルハンドル<IN>等からの入力時はdecodeが必要
# ファイルハンドル<OUT>等への出力時はencodeが必要
our $debug=1;
print 'Year:';
our $year=<>;
chomp $year;
open(OUT,'>calender'.$year.'.html');
for (my $month=1;$month<=12;$month++) {
my $cal = new HTML::CalendarMonthSimple('year'=>$year,'month'=>$month);
# 色々カスタマイズ出来るようです。詳細はCPANの解説文を読んでね。
# $cal->border(10);
# $cal->header('Text at the top of the Grid');
# $cal->setcontent(14,"Valentine's Day");
# $cal->setdatehref(14, 'http://localhost/');
# $cal->addcontent(14,"<p>Don't forget to buy flowers.");
# $cal->addcontent(13,"Guess what's tomorrow?");
# $cal->bgcolor('pink');
print OUT $cal->as_HTML;
}
close(OUT);
print '[Finish!]';
<>;
exit;
#----------------------------------
sub en_sjis
{
my ($buf)=@_;
encode('cp932',$buf);
}
sub de_sjis
{
my ($buf)=@_;
decode('cp932',$buf);
}
sub en_utf8
{
my ($buf)=@_;
encode('utf-8',$buf);
}
sub de_utf8
{
my ($buf)=@_;
decode('utf-8',$buf);
}
sub en_euc
{
my ($buf)=@_;
encode('euc-jp',$buf);
}
sub de_euc
{
my ($buf)=@_;
decode('euc-jp',$buf);
}
sub vv
{
my($Name,$Value)=@_;
if($debug) {
print $Name.'=['.$Value.']',"\n";
}
}