有没有办法在单个语句中将某些函数的返回值编译为正则表达式?

我需要构建一个与给定哈希中的任何键匹配的正则表达式。这可以通过以下方式轻松实现

my $string = join('|', keys %hash);
my $regex = qr/$string/;

where %hash is the hash in question. Out of curiosity: Is there a way to circumvent introducing the dummy variable $string and directly compile the return value of an arbitrary function into a regex (other than defining a custom sub or prototype)? Formulated differently: Does qr also have a functional form (like readpipe for qx)?

提前致谢!

评论
  • 被窝里=
    被窝里= 回复

    You can interpolate arbitrary code into any double-quotish construct (qq, qr, qx). $foo interpolates a scalar variable. ${ code-returing-a-scalar-reference } interpolates arbitrary code. So to avoid the dummy variable, you do:

    my $regex = qr/${ \join('|', keys %hash) }/;
    

    But as mentioned in comment, if you want to match only string equal to one of the keys, you want to add \A (or ^) and \z anchors. Otherwise you will match any string containing one of the keys.

    如果您的键可能包含正则表达式元字符,则您还想引用它们,例如:

    my $regex = qr/\A(?:${ \join('|', map quotemeta, sort keys %hash) })\z/;