2016-07-22 72 views
0

我在我的perl脚本中加载和打印制表符分隔的文件。然而,我的输入文件($ table1)的最后一列是空的,我不想在我的输出文件($ table3)中打印这个。我该如何以及在哪里做这件事? '打开'后或在'print $ table3'结束后?perl删除制表符分隔文件的最后一列

这是我的脚本的一部分(...表示不代码重要的这个问题)

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

use Data::Dumper; 
local $Data::Dumper::Useqq = 1; 
use Getopt::Long qw(GetOptions);; 

... 

open(my $table1,'<', $input) or die "$! - [$input]"; #input file 
open(my $table3, '+>', $output) || die ("Can't write new file: $!"); #output file 

... 

chomp(my @header_for_table1 = split /\t/, <$table1>); 

print $table3 join "\t", @header_for_table1, "name1", "name2", "\n"; 

{ 
    no warnings 'uninitialized'; 
    while(<$table1>){ 
     chomp; 
     my %row; 
     @row{@header_for_table1} = split /\t/; 
     print $table3 join ("\t", @row{@header_for_table1}, 
        @{ $lookup{ ... } 
         // [ "", "" ] }), "\n"; 
} 
} 

回答

1

你可以只pop @header_for_table1这将删除最后一个头,因此少了一个列存储在散片。但我想,“额外”列有来自像这样的代码具有换行符在join "\t", ..., "\n"参数列表,所以这将是最好只是立即与s/\t?\n\z//换行符之前删除的标签,而不是使用chomp

我建议您在join参数周围放一些括号,否则您将在每行末尾创建更多带有备用选项卡的文件。这里是你已经显示的代码的重构,这使得这个和其他一些改进

#! /usr/bin/perl 

use strict; 
use warnings; 

use Data::Dumper; 
local $Data::Dumper::Useqq = 1; 
use Getopt::Long qw(GetOptions); 

my ($input, $output); 
my %lookup; 

...; 

open my $in_fh, '<', $input or die "$! - [$input]"; 

...; 

my @header = do { 
    my $header = <$in_fh>; 
    $header =~ s/\t?\n\z//; 
    split /\t/, $header; 
}; 

open my $out_fh, '>', $output or die "Can't write new file: $!"; 

print $out_fh join("\t", @header, qw/ name1 name2 /), "\n"; 

while (<$in_fh>) { 
    s/\t?\n\z//; 

    my @row = split /\t/; 

    my $names = $lookup{ ... }; 
    my @names = $names ? @$names : ('', ''); 

    print $out_fh join("\t", @row, @names), "\n"; 
} 
相关问题