Perl,从两个文件中读取并写入第三个文件

时间:2011-04-11 05:25:18

标签: perl file-io

我无法让我的程序运行。基本上,我从两个文件读入,然后将数据写入一个。任何人都可以指出问题是什么?我一直在尝试写入文件的print OUT语句中获得有关实例化的错误。这是我的代码:

print "Please input file name \n";
$infile=<DATA>;
$infile2=<DATA>;

open IN, "$infile";
open JUNK, "$infile2";
open OUT, '>' ,'convertedback.txt';

$line = <IN>;
$line2 = <JUNK>;

#pull first line from sample (name 1)
print OUT "$line";
$line =<IN>;
#pull sequence line from FASTQ
print OUT "$line";
#pull line from quality file *2
print OUT "$line2";
$line2 =<JUNK>;
print OUT "$line2";

#Repeat until EOF
while($line =<IN>) {#for lines 5 to end

#Build Line 1
print "line 1 inf (name) is\n";
print $line2;
print OUT "$line2";


#Build Line 2
print "line 2 inf (seq) is\n";
print $line;
print OUT "$line";

#Build Line 3
$line2 =<JUNK>;
print "line 3 inf (quality) is\n";
print $line2;
print OUT "$line2";

#Build Line 4
$line2 =<JUNK>;
print "line 3 inf (quality) is\n";
print $line2;
print OUT "$line2";

}#while $line=<IN>
close (IN);
close (OUT);

print "Done!\n";

__DATA__
outfilenew.txt
sample.qualities

1 个答案:

答案 0 :(得分:6)

使用strict并在脚本的开头使用warnings

使用三个参数open ,例如

open(my $fh, '<', "input.txt") or die $!;

使用 while循环来读取文件中的行,

while(my $line = <>){
   #do something
}

脚本看起来像,

use strict;
use warnings;
print "Please input file name \n";
my $infile=<DATA>;
my $infile2=<DATA>;

open(my $in,'<', "$infile") or die $!;
open(my $junk,'<',"$infile2") or die $!;
open(my $out, '>' ,'convertedback.txt') or die $!;

my $line = <$in>;
my $line2 = <$junk>;

#pull first line from sample (name 1)
print $out "$line";
$line =<$in>;
#pull sequence line from FASTQ
print $out "$line";
#pull line from quality file *2
print $out "$line2";
$line2 =<$junk>;
print $out "$line2";

#Repeat until EOF
while($line =<$in>) {#for lines 5 to end

#Build Line 1
print "line 1 inf (name) is\n";
print $line2;
print $out "$line2";


#Build Line 2
print "line 2 inf (seq) is\n";
print $line;
print $out "$line";

#Build Line 3
$line2 =<$junk>;
print "line 3 inf (quality) is\n";
print $line2;
print $out "$line2";

#Build Line 4
$line2 =<$junk>;
print "line 3 inf (quality) is\n";
print $line2;
print $out "$line2";

}#while $line=<IN>
close ($in);
close ($out);

print "Done!\n";

__DATA__
outfilenew.txt
sample.qualities