How to return values from Perl block in template toolkit

93 Views Asked by At

I am working on template toolkit script. My script needs to convert a hexadecimal number to binary number and need to apply that binary number for i2c programming. I am stuck to return binary value and use those bits to program i2c.

[% MACRO i2c_write(rv,address,data) PERL -%]
my %rv;
my $address = hex($stash->get('address'));
my $data = hex($stash->get('data'));
my $bin_add = sprintf("%08b",$address);
my $bin_data = sprintf("%08b",$data);
$rv{bin_address} = $bin_add;
$rv{bin_data} = $bin_data;
[% END -%]

[% i2c_write(bin_value,'0x10','0x3B') %]

Expected output:
bin_value.bin_address = 00010000
bin_value.bin_data    = 00111011

I want to parse this bin_value.bin_address and bin_value.bin_data to another MACRO (still writing the MACRO).

In Another MACRO, will take each bit and print each bit

1

There are 1 best solutions below

1
Håkon Hægland On

It seems like you want to pass the name of a hash to the macro and store the values inside that hash. You can use the stash for that, for example:

p.pl:

use v5.38;
use Template;

my $template = Template->new({
    INCLUDE_PATH => '.',  # or specify your own directory
    EVAL_PERL    => 1,    # enable Perl code in template
});
my $vars = {
    bin_value => {
        bin_address => '',
        bin_data => '',
    }
};
$template->process('example.tt', $vars) || die $template->error();

example.tt:

[% MACRO i2c_write(rv_name, address, data) PERL -%]
    my $hash_name = $stash->get('rv_name');
    my $rv =  $stash->get($hash_name);
    my $address = hex($stash->get('address'));
    my $data = hex($stash->get('data'));
    $rv->{bin_address} = sprintf("%08b", $address);
    $rv->{bin_data} = sprintf("%08b", $data);
[% END -%]
[% i2c_write('bin_value', '0x10', '0x3B') -%]
[% bin_value.bin_address %]

Output:

00010000