我正在尝试在Perl中创建一个程序,它将读取数千个字符,并尝试查找匹配的字符串。我需要打印出字符串加上接下来的五个字母。我还需要打印出找到它的位置,即输入多少个字母。我对Perl很新。我现在正在课堂上学习。
这是我到目前为止的代码:
#!/usr/bin/perl
$sequence = 'abcd';
$fileName = 'file.txt';
#Opening file
unless (open(fileName, $fileName)) {
print "Cannot open file.";
exit;
}
@tempArr = <fileName>; #Adding the lines to an array
close fileName; #closing the file
$characters = join('', @tempArr); #making it a clean string
$characters =~ s/\s//g; #removing white lines
if (characters =~ m/$sequence/i) {
#Print $sequence and next five characters
}
else {
print "Does not contain the sequence.";
}
exit;
file.txt将如下所示:
aajbkjklasjlksjadlasjdaljasdlkajs
aabasdajlakjdlasdjkalsdkjalsdkjds
askdjakldamwnemwnamsndjawekljadsa
abcassdadadfaasabsadfabcdhereeakj
我需要打印出“abcdheree”
答案 0 :(得分:2)
打印$sequence
&amp;在它之后的5个字符,尝试使用:
if ($characters =~ m/$sequence.{5}/i) {
print "$&\n";
(您忘记了$
上的characters
)
注意强>
.
表示任何字符{5}
是量词open
时,请使用以下3个参数:open my $fh, "<", "$file" or die $!;
请参阅http://perldoc.perl.org/perlopentut.html use strict; use warnings;
放在脚本的顶部$
变量(你错过很多变量)my
声明变量foreach my $line (@tempArr) { #process $line }
@melTemp1
<强>最后强>
#!/usr/bin/perl
use strict; use warnings;
my $sequence = 'abcd';
my $fileName = 'file.txt';
#Opening file
open my $fh, "<", $fileName or die "Cannot open file. [$!]";
my @tempArr = <$fh>; #Putting the file handle into an array
close $fileName; #closing the file handle
my $characters = join('', @tempArr); #making it a big string
$characters =~ s/\s//g; #removing white spaces & tabs
if ($characters =~ m/$sequence.{5}/i) {
print "$&\n";
}
else {
print "Does not contain the sequence.";
}