我的程序包含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? –