use strict;
use Template ();
use Scalar::Util qw( looks_like_number );
sub fmt_currency {
my( $txt ) = @_;
return $txt unless looks_like_number( $txt );
if( $txt < 0 ) {
$txt = '(' . abs( $txt ) . ')'
} else {
## maybe wrap $txt with a pos span . . .
}
return $txt;
}
my $t = Template->new(
FILTERS => { fmt_currency => \&fmt_currency },
## ...
);
my $data = { qw/foo 1.23 bar -3.45 baz quux/ };
my %tmpl_src = <process( \$tmpl_src, $data, \*STDOUT );
exit 0;
__END__
1.23 (3.45) quux
####
#!/opt/local/bin/perl
use strict;
use Template ();
use Scalar::Util qw( looks_like_number );
sub fmt_currency_factory {
my ($ctx, $fmt) = @_;
$fmt = "%0.4f" unless defined $fmt;
return sub {
my ($txt) = @_;
return $txt unless looks_like_number($txt);
my $val = sprintf( $fmt, abs($txt) );
if ( $txt < 0 ) {
$txt = '(' . $val . ')';
}
else {
$txt = $val;
}
return $txt;
}
}
my $t = Template->new(
FILTERS => { fmt_currency => [ \&fmt_currency_factory, 1 ] },
## ...
);
my $data = { qw/foo 1.23 bar -3.45 baz quux/ };
my $tmpl_src = <process( \$tmpl_src, $data, \*STDOUT )
or die $t->error();
__END__
1.2300
(3.5)
quux