我的程序包含ascii.txt以匹配来自它的模式。 我的程序是执行sed
命令,只是为了尝试编写perl代码,因为我正在学习perl。在Perl中匹配正则表达式
#!/usr/bin/perl
# sed command implementation
use strict;
use warnings;
use subs qw(read_STDIN read_FILE usage);
use IO::File;
use constant {
SEARCH_PRINT => 0,
};
our $proj_name = $0;
main(@ARGV);
sub main
{
if(scalar @_ == 2) {
read_FILE @_;
}
else {
usage
}
}
sub read_FILE {
my ($sed_script, $file_name) = @_;
my $parsed_val = parse_sed_script($sed_script);
if($parsed_val == SEARCH_PRINT) {
search_print_lines($sed_script, $file_name);
}
}
sub parse_sed_script {
my $command = shift or return;
if($command =~ /^\/([^\/].)*\/$/) {
return SEARCH_PRINT;
}
}
sub search_print_lines {
my ($script, $file) = @_;
my $fh = IO::File->new($file, "r") or error("no file found $file");
while($_ = $fh->getline) {
print if $_ =~ $script
}
}
sub usage {
message("Usage: $proj_name sed-script [file]")
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
当我从shell执行:sed.pl /Test/ ascii.txt
我发现print if $_ =~ $script
,不会因为正则表达式的执行存储在标量
的ascii.txt包含。
Test 1
REGEX TEST
当我使用print $script
在search_print_lines
子程序它打印用户
我不明白,我需要一些解释。 –
如果你发送“/ Test /”,它不会匹配“REGEX TEST”,因为“REGEX TEST”不包含任何斜杠。那有意义吗?如果这是你不了解的其他内容,请告诉我,我会尽力澄清。 – Jeremy
是的,我知道这一点,但我不明白/ \/$ script \ //和eval? –