Can I create Perl Regex from a set of hash keys

(related to the previous question: Do I need to reset the Perl hash index? )

I have a hash included in a file that is defined as follows:

%project_keys = (
    cd     => "continuous_delivery",
    cm     => "customer_management",
    dem    => "demand",
    dis    => "dis",
    do     => "devops",
    sel    => "selection",
    seo    => "seo"
);

I need to check if the title of the review has the correct format, and if so, a link to a separate URL.

For example, if the title of the review

"cm1234 - Do some CM work"

then I want a link to the following URL:

http://projects/customer_management/setter/1234

I am currently using the following (hard-coded) regular expression:

if ($title =~ /(cd|cm|dem|dis|do|sel|seo)(\d+)\s.*/) {
    my $url = 'http://projects/'.$project_keys{$1}.'/setter/'.$2
}

but obviously, I would like to create a regular expression from the hash keys themselves (the hash example above will change quite often). I thought about just naively concatenating keys as follows:

# 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
}

but a) it does not work as I would like, and b) I assume that there is a much better way for Perl to do this. Or is there?

+4
1

+ . Perl, .. join.

:

my $project_match = join '|', map quotemeta, keys %project_keys;

if ($title =~ /($project_match)(\d+)\s/) {
   my $url = 'http://projects/'.$project_keys{$1}.'/setter/'.$2;
   # Something with $url
}

quotemeta - , , . , .

.* , " - , , ", . , .

+6

Source: https://habr.com/ru/post/1531264/


All Articles