在一串字符中查找序列并将其与随后的字符一起打印出来

时间:2012-11-08 03:16:00

标签: regex perl

我正在尝试在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”

1 个答案:

答案 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.";
}