我有一个文本文件,我正在尝试通过将1添加到它来调整第二列。我试着调整我们在课堂上练习的代码,但进展不是很好。这就是我当前代码的样子。如果可能,我想使用open函数。
use strict; use warnings;
open(my $in, '<first5.txt') or die ("Cannot execute");
open(my $out, '>first5.txt') or die ("Cannot execute");
while(<$in>){
chomp ($in);
my@input = split("\t", $in);
print("New chromosome position:",$input[1]+1, "\n");
}
close $in;
close $out;This is the original first5.txt
chr10 50005 50005 CHH:0 0 +
chr10 50006 50006 CHH:0 0 +
chr10 50013 50013 CHH:0 0 +
chr10 50014 50014 CHH:0 0 +
chr10 50021 50021 CHH:0 0 +
This is my desired outcome
chr10 50006 50005 CHH:0 0 +
chr10 50007 50006 CHH:0 0 +
chr10 50014 50013 CHH:0 0 +
chr10 50015 50014 CHH:0 0 +
chr10 50022 50021 CHH:0 0 +任何帮助都将不胜感激。
发布于 2021-03-10 01:17:51
while(<$in>)在$_中读入一行-所以chomp; my @input = split/\t/;是你应该做的。但是,您不应该同时为输入和输出打开相同的文件。这将截断文件(在Posix上)或失败(在Windows上)。
以下是建议的调整:
#!/usr/bin/perl
use strict;
use warnings;
my $inputfile = 'first5.txt';
my $outputfile = 'first5.TMP'; # write to a temporary file
open(my $in, '<', $inputfile) or die ("Cannot open $inputfile: $!");
open(my $out, '>', $outputfile) or die ("Cannot open $outputfile: $!");
while(<$in>) { # read a line into $_
chomp; # chomp $_
my @input = split/\t/; # split $_ on \t
++$input[1]; # add 1 to col 1
print $out join("\t", @input) . "\n"; # print result to outputfile
}
close $in;
close $out;
rename $outputfile, $inputfile; # move the temporary into place发布于 2021-03-10 01:17:33
#!/usr/bin/perl
use strict;
use warnings;
open my $in, '<', 'first5.txt' or die $!;
open my $out, '>', 'first5.new' or die $!;
while (<$in>) {
chomp;
my @columns = split /\t/;
++$columns[1];
print {$out} join "\t", @columns;
print {$out} "\n";
}
close $out;
rename 'first5.new', 'first5.txt' or die $!;我所做的更改:
发布于 2021-03-10 17:31:37
其他人已经指出了同时读取和写入同一文件的问题。
我只想指出,您当前的代码实际上从未写入输出文件。其中,您拥有:
print("New chromosome position:",$input[1]+1, "\n");你可能想要:
print $out "New chromosome position:",$input[1]+1, "\n";https://stackoverflow.com/questions/66551449
复制相似问题