简体   繁体   English

Perl Template :: Toolkit正则表达式匹配两个值

[英]Perl Template::Toolkit regex matching either values

I am trying to match either of the string in the Perl Template::Toolkit module. 我正在尝试匹配Perl Template::Toolkit模块中的任一字符串。

url is getting its value from the script. url从脚本中获取其价值。

[% 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 我认为在Template::Toolkit使用正则表达式有点尴尬,但是在这种情况下,您可以编写

[% 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 如果您需要更复杂的东西,那么您可能会误解模板的作用,但是您始终可以在Perl中评估布尔条件并将该值传递到模板中


Update 更新资料

Or you could use SWITCH , like this 或者您可以像这样使用SWITCH

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

You can use the match virtual method to test a regexp. 您可以使用match virtual方法测试一个正则表达式。 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. 或者,对脚本中的URL进行匹配,然后将布尔结果传递给模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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