简体   繁体   中英

Perl Template::Toolkit regex matching either values

I am trying to match either of the string in the Perl Template::Toolkit module.

url is getting its value from the script.

[% IF url == ("a/b/c" | "d/e/f") %]

Is this the right way of doing it? I looked at the documents. It mentioned the 'matches' method, but I am looking for a simpler way of doing it.

I think it's a little awkward to use regular expressions in Template::Toolkit , but in this case you can just write

[% IF url == 'a/b/c' or url == 'd/e/f' %]

If you need anything more complex then you're probably misunderstanding the rôle of templates, but you can always evaluate a Boolean condition within Perl and pass that value into the template


Update

Or you could use SWITCH , like this

[% SWITCH url %]
[%   CASE [ 'a/b/c', 'd/e/f' ] %]
       ...
[% END %]

You can use the match virtual method to test a regexp. This is as simple as it gets.

use strict;
use warnings;
use Template;

my $t = Template->new;
$t->process( \*DATA, { urls => [qw(
    http://example.com/a/b/c
    http://example.com/xyz
    http://example.com/x/d/e/f
)] } );

__DATA__
[% FOREACH url IN urls %]
  [%- IF url.match('a/b/c|d/e/f') %]
    [%- url %] - match
  [%- ELSE %]
    [%- url %] - NO match
  [%- END %]
[% END %]

Outputs:

http://example.com/a/b/c - match
http://example.com/xyz - NO match
http://example.com/x/d/e/f - match

Alternatively, perform the match on the URL in your script then pass the boolean outcome to the template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM