Template::Plugin::Tax

消費税計算のために作ってみた。

package Template::Plugin::Tax;

use strict;
use warnings;
our $VERSION = '0.01';

require Template::Plugin;
use base qw(Template::Plugin);

our $FILTER_BASE_NAME = 'tax';
our $DEFAULT_TAX      = 5; # 5%

sub new {
    my($self, $context, @args) = @_;
    my $inc_name = sprintf "to_inc_%s" , $args[0] || $FILTER_BASE_NAME;
    my $enc_name = sprintf "to_enc_%s" , $args[0] || $FILTER_BASE_NAME;
    $context->define_filter($inc_name, \&to_inc_tax_factory, 1);
    $context->define_filter($enc_name, \&to_enc_tax_factory, 1);
    return $self;
}

sub to_inc_tax_factory {
    my ($context,$tax) = @_;
    $tax ||= $DEFAULT_TAX;
    return sub {
        my $money = shift;
        return int(($money + $money / 100 * $tax)+0.5);
    };
}

sub to_enc_tax_factory {
    my ($context,$tax) = @_;
    $tax ||= $DEFAULT_TAX;
    return sub {
        my $money = shift;
        return int(($money * 100 / (100 + $tax))+0.5);
    };
}

1;

__END__

[% USE Tax %]

[% price = 100 %]
[% price|to_inc_tax %] # 105

[% price = 210 %]
[% price|to_enc_tax %] # 200

消費税50%の時代が到来
[% price = 100 %]
[% price|to_inc_tax(50) %] # 150

同じのCPANにあるかな?