首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用open函数将1添加到文本文件中的列

使用open函数将1添加到文本文件中的列
EN

Stack Overflow用户
提问于 2021-03-10 01:00:12
回答 3查看 59关注 0票数 1

我有一个文本文件,我正在尝试通过将1添加到它来调整第二列。我试着调整我们在课堂上练习的代码,但进展不是很好。这就是我当前代码的样子。如果可能,我想使用open函数。

代码语言:javascript
复制
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;
代码语言:javascript
复制
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   +

任何帮助都将不胜感激。

EN

回答 3

Stack Overflow用户

发布于 2021-03-10 01:17:51

while(<$in>)$_中读入一行-所以chomp; my @input = split/\t/;是你应该做的。但是,您不应该同时为输入和输出打开相同的文件。这将截断文件(在Posix上)或失败(在Windows上)。

以下是建议的调整:

代码语言:javascript
复制
#!/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
票数 4
EN

Stack Overflow用户

发布于 2021-03-10 01:17:33

代码语言:javascript
复制
#!/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 $!;

我所做的更改:

  • 使用open的3参数版本。使用变量名更安全。
  • 包含打开失败的原因($!)在错误消息中。
  • 不要为输入和输出打开相同的文件。
  • 不要占用句柄。
  • 使用更好的变量名。
  • 您可以使用++递增split的第一个参数是正则表达式。<代码>H216<代码>F217
票数 3
EN

Stack Overflow用户

发布于 2021-03-10 17:31:37

其他人已经指出了同时读取和写入同一文件的问题。

我只想指出,您当前的代码实际上从未写入输出文件。其中,您拥有:

代码语言:javascript
复制
print("New chromosome position:",$input[1]+1, "\n");

你可能想要:

代码语言:javascript
复制
print $out "New chromosome position:",$input[1]+1, "\n";
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66551449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档