package Template;
use strict;
use vars qw(@ISA @EXPORT @EXPORT_OK);

use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(template template_string);
@EXPORT_OK = qw(read_tmplfile);

my %template = ();

#---------------------------------------------------------------------------
#
# テンプレートを当てはめる
#
#---------------------------------------------------------------------------

#
# テンプレートファイルの一気読み
#
sub read_tmplfile {
    my ($tmplfile, $text) = @_;

    local $/;  # 一気読みモード
    local *F;  # ローカルのファイルハンドル
#    open(F, "< $tmplfile\0") || return;
    open(F, "< $tmplfile\0") || die "($tmplfile)\n";
    ${$text} = <F>;
    close(F);
}

#
# ファイル（の中味）をテンプレートとして適用
#
sub template {
    my ($tmplfile, $fields) = @_;
    my $text;

    unless ($template{$tmplfile}) {
	&read_tmplfile($tmplfile, \$text);
	$template{$tmplfile} = $text;
    }
    else {
	$text = $template{$tmplfile};
    }

    # Replace the quoted words by the values of %{$fields} hash
    $text =~ s{ %%(.*?)%% }{ exists($fields->{$1}) ? $fields->{$1} : ""}gsex;

    return $text;
}

#
# 文字列をテンプレートとして適用
#
sub template_string {
    my ($text, $fields) = @_;
    $text =~ s{ %%(.*?)%% }{ exists($fields->{$1}) ? $fields->{$1} : ""}gsex;
    return $text;
}

1;
