【发布时间】:2014-04-16 00:13:10
【问题描述】:
(与上一题相关:Do I need to reset a Perl hash index?)
我有一个来自文件的哈希值,定义如下:
%project_keys = (
cd => "continuous_delivery",
cm => "customer_management",
dem => "demand",
dis => "dis",
do => "devops",
sel => "selection",
seo => "seo"
);
我需要检查评论标题的格式是否正确,如果是,请链接到单独的 URL。
例如,如果评论标题是
"cm1234 - Do some CM work"
然后我想链接到以下网址:
http://projects/customer_management/setter/1234
目前,我正在使用以下(硬编码)正则表达式:
if ($title =~ /(cd|cm|dem|dis|do|sel|seo)(\d+)\s.*/) {
my $url = 'http://projects/'.$project_keys{$1}.'/setter/'.$2
}
但显然我想从哈希键本身构建正则表达式(上面的哈希示例会经常更改)。我想过简单地将键连接如下:
# Build the regex
my $regex = '';
foreach my $key ( keys %project_keys ) {
$regex += $key + '|';
}
$regex = substr($regex, 0, -1); # Chop off the last pipe
$regex = '('.$regex.')(\d+)\s.*';
if ($title =~ /$regex/) {
my $url = 'http://projects/'.$project_keys{$1}.'/setter/'.$2
}
但是 a) 它没有像我希望的那样工作,并且 b) 我认为有更好的 Perl 方法可以做到这一点。或者有吗?
【问题讨论】: