问题
Each record has 4 lines:
Like the following:
@NCYC36111a03.q1k bases 1 to 1576
GCGTGCCCGAAAAAATGCTTTTGGAGCCGCGCGTGAAAT
+
!)))))****(((***%%((((*(((+,**(((+**+,
There are two files in which 1 file corresponded to the other
there are an array of seqeunces A1 So read 1 record at a time from file 1. read record from file 2. if the sequence in record 1 file 1 (line 2) matches the seuqnece in the array A1, i print the record from file 2 to an output file so on...but the point is i need to read a record at a time.... how would i break out of the inner loop so that i can read the next record from the file 1 and then compare it to the next record in file 2
回答1:
If you ask about controlling nested loops you can do that with labels.
Example:
OUTER:
while(<>){
for(@something){
last OUTER;
}
}
See last for example.
回答2:
In case only lines with same number could ever match, you don't really need more than one loop. You can call reading operation (<>
, read
, sysread
) wherever you want. It only usually placed directly in loop because it conveniently returns undef and breaks it when work is done.
while(defined(my $first_line = <FIRST>)){
my $second_line = <SECOND>;
if($first_line eq $second_line){
print "match\n";
} else {
print "no match\n";
}
}
回答3:
From your sentence I need to check if the sequence matches any with the sequence from the second I gather that you want to check whether any lines in the two files match?
If you need to read a file several times then you can use seek
to rewind to the start of it without reopening it.
This program shows the idea.
use strict;
use warnings;
open my $fh1, '<', 'file1' or die $!;
open my $fh2, '<', 'file2' or die $!;
open my $out, '>', 'matches' or die $!;
while (my $line1 = <$fh1>) {
seek $fh2, 0, 0;
while (my $line2 = <$fh2>) {
if ($line1 eq $line2) {
print $out $line1;
last;
}
}
}
Edit
Your comment has changed the problem. Both files have four-line records and you want to compare the second line in corresponding records across the two files.
use strict;
use warnings;
open my $fh1, '<', 'file1' or die $!;
open my $fh2, '<', 'file2' or die $!;
open my $match, '>', 'matches' or die $!;
open my $nomatch, '>', 'nomatch' or die $!;
while (1) {
my (@data1, @data2);
for (1 .. 4) {
my $line;
$line = <$fh1>;
push @data1, $line if defined $line;
$line = <$fh2>;
push @data2, $line if defined $line;
}
last unless @data1 == 4 and @data2 == 4;
if ($data1[1] eq $data2[1]) {
print $match @data2;
}
else {
print $nomatch @data2;
}
}
回答4:
A full example :
#!/usr/bin/env perl
use strict;
use warnings;
open F1, "<", "/path/1";
open F2, "<", "/path/2";
@a1 = <F1>;
@a2 = <F2>;
for (0..$#a1) {
if ($a1[$_] eq $a2[$_]) {
print "MATCH line [$_]\n";
} else {
print "DOESN'T MATCH line [$_]\n";
}
}
来源:https://stackoverflow.com/questions/10899621/perl-while-loops-and-reading-lines