将正则表达式传递给perl子例程

时间:2013-12-17 23:45:52

标签: regex perl function parameters subroutine

情况

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

问题

当我尝试通过命令行运行Perl代码时,会开始生成错误。我试图将正则表达式传递给repeat子例程,我不确定如何正确执行此操作。我知道我可以使用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");

我尝试过:

基于这些来源:


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

感谢任何帮助!

2 个答案:

答案 0 :(得分:16)

要创建正则表达式以供日后使用,我们使用qr //:

my $regexp = qr/^Perl$/;

这会编译正则表达式以供以后使用。如果您的正则表达式出现问题,您会立即听到它。要使用此预编译的正则表达式,您可以使用以下任何一种方法:

# See if we have a match
$string =~ $regexp;

# A simple substitution
$string =~ s/$regexp/Camel/;

# Comparing against $_
/$regexp/;

答案 1 :(得分:5)

/.../这样的正式正则表达式字面值与$_匹配。要创建独立的正则表达式对象,请使用qr//引号:

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

(除非您知道何时以及为何需要,否则请不要调用&sub之类的潜艇。)