问题描述
例如:
我知道如何匹配www.domain.com/foo/21
sub foo : Path('/foo') Args(1) {
my ( $self, $c, $foo_id ) = @_;
# do stuff with foo
}
但是我如何匹配 www.domain.com/foo/21 或 www.domain.com/foo/21/bar/56 ?
But how can I match www.domain.com/foo/21 OR www.domain.com/foo/21/bar/56 ?
sub foo : <?> {
my ( $self, $c, $foo_id, $bar_id ) = @_;
# do stuff with foo, and maybe do some things with bar if present
}
谢谢
更新:按照 Daxim 的建议,我尝试使用 :Regex
Update:Following Daxim's suggestion, I tried to use :Regex
sub foo : Regex('foo/(.+?)(?:/bar/(.+))?') {
my ( $self, $c ) = @_;
my ( $foo_id, $bar_id ) = @{ $c->req->captures };
}
但这似乎不起作用;url 匹配,但 $bar_id 总是 undef.如果我从正则表达式的末尾删除可选操作符,那么它确实会正确捕获 $bar_id,但是必须同时存在 foo 和 bar 才能获得 url 匹配.我不确定这是 perl 正则表达式问题还是 Catalyst 问题.有什么想法吗?
But this doesn't seem to work; the url is matched, but $bar_id is always undef. If I remove the optional opperator from the end of the regex then it does capture $bar_id correctly, but then both foo and bar must be present to get a url match. I'm not sure if this is a perl regex issue, or a Catalyst issue. Any ideas?
更新:
正如 Daxim 指出的那样,这是一个正则表达式问题.我不明白为什么上面的正则表达式不起作用,但我确实找到了一个:
As Daxim points out, its a regex issue. I can't see why the above regex doesn't work, but I did manage to find one that does:
sub foo : Regex('foo/([^/]+)(?:/bar/([^/]+))?') {
my ( $self, $c ) = @_;
my ( $foo_id, $bar_id ) = @{ $c->req->captures };
}
(我没有像 Daxim 那样在捕获中使用 \d+,因为我的 ID 可能不是数字)
(I didn't use \d+ in the captures like Daxim did as my ids might not be numeric)
感谢大家的帮助和建议,我学到了很多关于在 Catalyst 中处理 url 的知识 :D
Thanks all for the help and suggestions, I learnt a lot about handling urls in Catalyst :D
推荐答案
查看.
尼克写道:
我不确定这是 perl 正则表达式问题还是 Catalyst 问题.有什么想法吗?
简单地尝试一下怎么样?
How about simply trying it out?
repl>>> $_ = '/foo/21/bar/56'
/foo/21/bar/56
repl>>> m|foo/(\d+)(?:/bar/(\d+))?|
$VAR1 = 21;
$VAR2 = 56;
repl>>> $_ = '/foo/21'
/foo/21
repl>>> m|foo/(\d+)(?:/bar/(\d+))?|
$VAR1 = 21;
$VAR2 = undef;
这篇关于在 Catalyst 控制器中处理可选 url 参数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!