情况
我正在创建一个简单的模板文件,该文件将有助于创建 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");
我尝试过的:
基于这些来源:
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/