在命令行上创建哈希后将其打印到输出文件中

printing a hash into an output file after creating it on the command line

我正在尝试使用创建的散列并将结果提取到输出文件中。我的脚本在下面。任何帮助将不胜感激。干杯。

first_file 数据样本

>nameID ABCD

second_file 数据样本

>nameID 0.5

我的 Perl 代码

my ( $first_file, $second_file ) = @ARGV;

my %name;

{
    open my $fh, '<', $first_file or die qq{Unable to open "$first_file": $!};

    my $key;
    while ( <$fh> ) {
        if ( /^>(\S+)/ ) {
            $key = ;
        }
        elsif ( /\S/ ) {
            chomp;
            $name{$key} .= $_;
        }
    }
}

open my $fh, '<', $second_file or die qq{Unable to open "$second_file": $!};
while ( <$fh> ) {
    if ( /^>(\S+)/ ) {
        printf "%s\t%s\n", , $name{} // 'undef';
    }
}

我遇到的问题是从命令行将 printf "%s\t%s\n", , $name{} // 'undef' 提取到输出文件中。

尝试以下操作。我已经稍微改变了你的正则表达式。请注意,我假设您的行以“>”字符开头,并且您在示例中使用的“--”不存在(否则,您的正则表达式将需要以 /^-->.[=15 开头=]

#!/usr/bin/perl
use warnings;
use strict;

my ( $first_file, $second_file ) = @ARGV;
my $write_file = 'output.txt';

my %name;

open my $fh1, '<', $first_file
  or die qq{Unable to open "$first_file": $!};

while ( <$fh1> ) {
    s/,//;
    if ( /^>\s+(\S+)\s+(\S+)/ ) {
        $name{} = ;
    }
}
close $fh1;

open my $fh2, '<', $second_file
  or die qq{Unable to open "$second_file": $!};

open my $wfh, '>', $write_file
  or die "Unable to open write file $write_file: $!";

while ( <$fh2> ) {
    s/,//;
    if ( /^>\s+(\S+)/ ) {
        printf $wfh "%s\t%s\n", , $name{} // 'undef';
    }
}

close $fh2;
close $wfh;

输入文件 1:

> 1, ABCD
> 2, XFSD
> 3, GDWE
> 4, MMDD

输入文件 2:

> 1, 0.5
> 4, 9.99
> 6, 22.22

输出文件:

1   ABCD
4   MMDD
6   undef

将输出重定向到文件所需要做的就是在命令行中指定它

program.pl file1.txt file2.txt > output.txt

我建议您这样做,这样您就可以在不编辑程序的情况下选择输出的发送位置