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

use*_*516 3 regex parameters perl grep

print grep /test/, "mytestphrase";
Run Code Online (Sandbox Code Playgroud)

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

use strict; 
use warnings;

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

    print grep $regex, $phrase;
}

testsub /test/, "mytestphrase";
Run Code Online (Sandbox Code Playgroud)

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

Use of uninitialized value $_ in pattern match (m//) at ./a.pl line 14.
Run Code Online (Sandbox Code Playgroud)

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

Tot*_*oto 5

像这样传递参数:

testsub qr/test/, "mytestphrase";
Run Code Online (Sandbox Code Playgroud)

也改变了$regexto 的使用/$regex/

#!/usr/bin/perl

use strict; 
use warnings;

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

testsub qr/test/, "mytestphrase";
Run Code Online (Sandbox Code Playgroud)

  • 您始终可以使用 [prototypes](http://perldoc.perl.org/perlsub.html#Prototypes),尽管覆盖 Perl 的正常行为不太可能赢得任何人气竞赛。 (2认同)