Terence Monteiro wrote:
> On Mon, Nov 09, 2009 at 12:36:52PM +0100, Robin Smidsrød wrote:
>> Terence Monteiro wrote:
>>> Hi,
>>>
>>> I needed a TT filter to convert bytes into units of kb, Mb, Gb, etc. I
>>> wrote a filter for this. Has anyone found such a module on CPAN or
>>> anywhere?
>>>
>>> e.g
>>> 1024 -> 1k
>>> 2560 -> 2.5k
>>>
>>> I was thinking of putting it up on CPAN if not already there?
>> There is always Number::Bytes::Human on CPAN. It worked for me. Someone
>> else on the list can probably tell you how to turn that into a TT filter.
> 
> Did you use the module in TT? I have already written it as a filter,
> because it seems better to use a filter than convert and send to TT or
> use the module directly with a Perl block.
> 

I just used something like this (not tested) to pass a function into the
template. Darren Chamberlain's suggestion looks much better, though. I
would suggest you use that one instead.

use Template;
use Number::Bytes::Human;

my $template = Template->new(
 VARIABLES => { format_bytes => \&format_bytes }
);

sub format_bytes {
    my $human = Number::Bytes::Human->new();
    my @numbers;
    while(my $number = shift @_) {
        push @numbers, $human->format($number);
    }
    return wantarray ? @numbers : $numbers[0];
}

-- Robin

_______________________________________________
templates mailing list
[email protected]
http://mail.template-toolkit.org/mailman/listinfo/templates

Reply via email to