nikos has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks!

I've been using Template Toolkit for a while but still haven't figured out how to do bitwise operations in template-toolkit. [% 8 and 1 %] is 1 as it does a logical 'and' not bitwise. Same thing if I put '&&' (a logical operator). And it doesn't understand a bitwise operator '&' like in C. Is there any way to do bitwise calculations?

Just a short test code:
#!/usr/bin/perl -w use strict; use Template; my $template=new Template; $template->process(\*DATA) || die $template->error; __DATA__ 8 and 1 = [% 8 and 1 %] (should be 0, if we use a bitwise operator) 8 or 1 = [% 8 or 1 %] (should be 9, if we use a bitwise operator)


Thank you in advance.

Edited

Replies are listed 'Best First'.
Re: Template toolkit binary operations
by Zaxo (Archbishop) on Oct 09, 2004 at 17:18 UTC

    The Template Toolkit language isn't really perl. It is primarily about text substitution, not computation. It's possible to embed real perl in a template with the PERL directive. Here's your code with that modification,

    #!/usr/bin/perl -w use strict; use Template; my $template=new Template( EVAL_PERL => 1); $template->process(\*DATA) || die $template->error; __DATA__ 8 and 1 = [% PERL %] print 8 & 1 [% END %] (should be 0, if we use a b +inary operator) 8 or 1 = [% PERL %] print 8 | 1 [% END %] (should be 9, if we use a bi +nary operator)
    When run, that produces,
    $ perl ttbin.pl 8 and 1 = 0 (should be 0, if we use a binary operator) 8 or 1 = 9 (should be 9, if we use a binary operator) $
    "Binary operator" usually refers to an op with two arguments, usually with infix semantics. We usually call the operators you wanted "bitwise". In perl, and and or are low-precedence versions of the logical operators && and ||.

    After Compline,
    Zaxo

      Thank you for your reply. I'll edit my post. Using Perl to do the trick is fine. I just thought there would be an easier way. I need something like [% IF a & 1 == 1 %]thumbnail[% ELSE %]picture[% END %].
Re: Template toolkit binary operations
by talexb (Chancellor) on Oct 09, 2004 at 17:18 UTC

    Is it possible for you to instead just flip into Perl instead of using TT2's native language?

    Alex / talexb / Toronto

    "Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds

      Yes, it's possible. It would be great if I can do everything in my template btw.
      I have a value for each item to determine what icons to show, and it's bitwise. eg 1 stands for a thumbnail, 2 - popular, 4 - new... It can be 5. It means it's a 'new thumbnail'.