regex - Perl如何将正则表达式传递给我的子例程,如grep

标签 regex perl parameters grep

print grep /test/, "mytestphrase";

使用 grep 语法,您可以传入不带引号的正则表达式。 我希望我的子程序具有如下相同的行为:

use strict; 
use warnings;

sub testsub {
    my $regex = shift;
    my $phrase = shift;

    print grep $regex, $phrase;
}

testsub /test/, "mytestphrase";

但是,它会在 testsub 调用之前尝试针对我的正则表达式评估 $_,并发出以下错误:

Use of uninitialized value $_ in pattern match (m//) at ./a.pl line 14.

是否可以像 grep 命令一样调用 testsub 以及必须如何修改子例程以支持它?

最佳答案

像这样传递参数:

testsub qr/test/, "mytestphrase";

$regex的使用也改为/$regex/:

#!/usr/bin/perl

use strict; 
use warnings;

sub testsub {
    my $regex = shift;
    my $phrase = shift;
    print grep /$regex/, $phrase;
}

testsub qr/test/, "mytestphrase";

关于regex - Perl如何将正则表达式传递给我的子例程,如grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24490481/

相关文章:

perl - 在 Perl 中,如何正确解析带引号的字符串的制表符/空格分隔文件?

java - 如何使用 Netbeans 将选项传递给 jar 文件

C - 将二维数组上的指针传递给函数

regex - 使用 HTACCESS 将页面重定向到其中包含问号的 URL?

regex - 如何在 Vim ex 命令中匹配正则表达式中的退格字符?

php - 解析 TO header 中符合 RFC 822 的地址

arrays - Perl 中的 HashMap

perl - 如果在文件中找到特定字符串,如何打印上面 10 行?

R Markdown 参数 - 我可以组合向量用作参数吗?

regex - POSIX 正则表达式 : Exclude a specified word in the list using Regex