字符串匹配搜索

时间:2012-02-01 21:21:06

标签: perl pattern-matching

这样的一个文本文件作为查询文件:

fooLONGcite
GetmoreDATA
stringMATCH
GOODthing

这样的另一个文本文件作为主题文件:

sometingfooLONGcite
anyotherfooLONGcite
matchGetmoreDATA
GETGOODthing
brotherGETDATA
CITEMORETHING
TOOLONGSTUFFETC

预期的结果是从主题文件中获取匹配的字符串,然后将其打印出来。所以,输出应该是:

sometingfooLONGcite
anyotherfooLONGcite
matchGetmoreDATA    
GETGOODthing

这是我的perl脚本。但它不起作用。你能帮我找到问题所在吗?谢谢。

#!/usr/bin/perl
use strict;

# to check the command line option
if($#ARGV<0){
    printf("Usage: \n <tag> <seq> <outfile>\n");
    exit 1;
}

# to open the given infile file
open(tag, $ARGV[0]) or die "Cannot open the file $ARGV[0]";
open(seq, $ARGV[1]) or die "Cannot open the file $ARGV[1]";

my %seqhash = ();
my $tag_id;
my $tag_seq;
my $seq_id;
my $seq_seq;
my $seq;
my $i = 0;

print "Processing cds seq\n";
#check the seq file
while(<seq>){ 
    my @line = split;
    if($i != 0){
        $seqhash{$seq_seq} = $seq;
        $seq = "";
        print "$seq_seq\n";
    }
    $seq_seq = $line[0];
    $i++;
}

while(<tag>){ 
    my @tagline = split; 
    $tag_seq = $tagline[0];
    $seq = $seqhash{$seq_seq};
    #print "$tag_seq\n";
    print "$seq\n";
    #print output ">$id\n$seq\n";
}
#print "Ending of Processing gff\n";

close(tag);
close(seq);

2 个答案:

答案 0 :(得分:1)

据我所知,你会找到一部分字符串的匹配,而不是一个完全匹配。这是一个执行我认为您正在寻找的脚本:

script.pl的内容。我考虑到查询文件很小,因为我将其所有内容添加到正则表达式:

use warnings;
use strict;

## Check arguments.
die qq[Usage: perl $0 <query_file> <subject_file>\n] unless @ARGV == 2;

## Open input files. Abort if found errors.
open my $fh_query, qq[<], shift @ARGV or die qq[Cannot open input file: $!\n];
open my $fh_subject, qq[<], shift @ARGV or die qq[Cannot open input file: $!\n];

## Variable to save a regex with alternations of the content of the 'query' file.
my $query_regex;

{
    ## Read content of the 'query' file in slurp mode.
    local $/ = undef;
    my $query_content = <$fh_query>;

    ## Remove trailing spaces and generate a regex.
    $query_content =~ s/\s+\Z//;
    $query_content =~ s/\n/|/g;
    $query_regex = qr/(?i:($query_content))/;
}

## Read 'subject' file and for each line compare if that line matches with 
## any word of the 'query' file and print in success.
while ( <$fh_subject> ) { 
    if ( m/$query_regex/o ) { 
        print
    }   
}

运行脚本:

perl script.pl query.txt subject.txt

结果:

sometingfooLONGcite
anyotherfooLONGcite
matchGetmoreDATA
GETGOODthing

答案 1 :(得分:0)

您当前的代码没有多大意义;你甚至引用了你没有指定任何东西的变量。

您需要做的就是将第一个文件读入哈希值,然后根据该哈希值检查第二个文件的每一行。

while (my $line = <FILE>)
{
    chomp($line);
    $hash{$line} = 1;
}

...

while (my $line = <FILE2>)
{
    chomp($line);
    if (defined $hash{$line})
    {
        print "$line\n";
    }
}
相关问题