regex - 将正则表达式传递给 perl 子程序

标签 regex perl function parameters subroutine

情况

我正在创建一个简单的模板文件,该文件将有助于创建 future 的脚本,以便在 *nix 系统上通过命令行执行各种任务。作为其中的一部分,我可能会要求用户输入需要根据源代码中提供的正则表达式进行验证的数据。

问题

当我尝试通过命令行运行 Perl 代码时,开始生成错误。我试图将正则表达式传递到重复子例程中,但我不确定如何准确执行此操作。我知道我可以使用 eval 执行字符串,但是由于惯例,这是我想避免的事情。

错误:

Use of uninitialized value $_ in pattern match (m//) at scripts/template line 40.
Use of uninitialized value $resp in concatenation (.) or string at scripts/template line 37.

编码:
#!/usr/bin/env perl

use strict;
use warnings;
use Cwd;
use Term::ANSIColor;
use Data::Dumper;

my $log = "template.log";
my $task = "template";
my $cwd = getcwd();
my $logPath = $cwd . "/". $log;

print ucfirst($task) . " utility starting...\n";
system("cd ~/Desktop");
system("touch " . $log);
&writeLog("Test");

sub writeLog {
    open(my $fh, '>>', $logPath) or die "Could not open file '$log' $!";
    print $fh $_[0] . localtime() . "\n";
    close $fh;
    return 1;
}

sub ask {
    my $question = $_[0];
    my $input = $_[1];
    my $resp = <>;
    chomp($resp);
}

sub repeat {
    my $pat = $_[0];
    my $resp = $_[1];
    print $pat . "\n";
    print $resp . "\n";
}

&repeat(/foo|bar/i, "y");

我尝试过的:

基于这些来源:
  • Match regex and assign results in single line of code
  • How to assign result of a regex match to a new variable, in a single line?

  • sub repeat {
        my $pat =~ $_[0];
        my $resp = $_[1];
        if($pat !~ $resp) {
            print "foo\n";
        } else {
            print "bar\n";
        }
    }
    

    任何帮助表示赞赏!

    最佳答案

    为了创建一个正则表达式供以后使用,我们使用 qr//:

    my $regexp = qr/^Perl$/;
    

    这将编译正则表达式以供稍后使用。如果您的正则表达式有问题,您会立即听到。要使用此预编译的正则表达式,您可以使用以下任何一种:
    # See if we have a match
    $string =~ $regexp;
    
    # A simple substitution
    $string =~ s/$regexp/Camel/;
    
    # Comparing against $_
    /$regexp/;
    

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

    相关文章:

    linux - 如何将变量作为键传递给perl中的散列

    mysql - VB.Net 不使用数据库数据填充数组

    python-3.x - Python - 迭代列表 -Lambda

    php - 如何使用 PHP 正则表达式压缩空格字符?

    ruby-on-rails - ruby /rails : How can I replace a string with data from an array of objects?

    python - 从 SRE_Match 对象获取跨度和匹配值 (Python)

    regex - 使用正则表达式重命名命令不起作用

    perldoc 不显示已安装 perl 模块的文档

    perl - Perl 脚本中的 Bash 命令

    javascript - 从对象 : object. 中调用函数 function()