Perl grep 以数组为值的散列

Perl grep into hash with arrays as values

我正在构建一个具有以下路由的小型 Web 服务

my %routes = (
  'News' => ['^news', '^news\/?(.*)?', '^news\/(\d+)\/(edit|delete|update)'],
  'User' => ['^users', '^users\/?(.*)?', '^users\/(\d+)\/(edit|delete|update)'],
);

%routes中的每个key都是一个模块,对应的数组保存着模块支持的可能的请求。

因此,如果请求是 "news/3/edit",则应找到并返回新闻模块。

我想做的是 grep 正确的键,如果它的对应数组值与传入的请求匹配。

你应该使用一个可以让你创建路由的框架,它会在长运行中简单得多。不过,在回答您的一般问题时,您可以这样做:

use strict;
use warnings; 

use List::Util qw(any);

my %routes = (
  'News' => ['^news', '^news\/?(.*)?', '^news\/(\d+)\/(edit|delete|update)'],
  'User' => ['^users', '^users\/?(.*)?', '^users\/(\d+)\/(edit|delete|update)'],
);

sub match { 
   my ($string_to_match) = @_;

   foreach my $module ( keys %routes ) {
      return $module if any { $string_to_match =~ m/$_/ } @{$routes{$module}}
   }

   return;
}

然后你可以这样说:

use strict; 
use warnings; 

use feature qw(say);
use MatchRoutes; # or whatever your package is called

say MatchRoutes->new->match('news/3/edit');