打印标题行和文件中的每一行,并排在列中

时间:2015-12-27 21:25:22

标签: perl

您好我有一个tsv文件,我试图打印标题行和文件的每一行,即在列中。  不幸的是我对如何在打印声明中加入行感到困惑。

#!/usr/bin/perl
use strict;
use warnings;
local $" = "'\n'";      
my @temp;

while (<DATA>) {
    chomp;
    my @columns = join "\t", $_;
    push @temp, @columns;
}

my $Header_row = shift (@temp);
my @head;
my $abc;
my @abc = split(/\t/,$Header_row);
        for my $abc(@abc) {
        push @head, $abc ."\n";


}
my @roows;
my $elements;
        foreach (@temp){
        chomp;
my $line = $_;
my @elements = split ("\t", $line);
        for  $elements(@elements){
        push @roows, $elements ."\n";

}
}
        #print @head, $abc ."\n";
        #print @roows, $elements ."\n";



__DATA__
Year    Tonn    Class   Cargo   Type
88  61  T   Rice    Truck
89  55  G   Corn    Train   
92  93  S   Peas    Ship

必需输出

输出

Year    88
Tonn    61  
Class   T   
Cargo   Rice    
Type    Truck

Year    89
Tonn    55  
Class   G   
Cargo   Corn    
Type    Train

Year    92
Tonn    93  
Class   S   
Cargo   Peas    
Type    Ship

2 个答案:

答案 0 :(得分:2)

根据您的来源,这应该可以解决问题:

convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
    // Base64DataURL
});

注意 - 您可以将“读取标题”进一步浓缩为:

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

#read the header line into @header;     
my $header_line = <DATA>;
chomp $header_line;
chomp ( my @header = split ( ' ', $header_line ); 

#iteraate data fh    
while ( <DATA> ) {
    #strip linefeed 
    chomp;
    #read this row into a hash 
    my %row; @row{@header} = split;
    #print this hash in the same order as the header.  
    #note - $_ is set to each element of header in turn when doing this. 
    print "$_\t$row{$_}\n" for @header;
    #insert extra linefeed
    print "\n";
}

__DATA__
Year    Tonn    Class   Cargo   Type
88  61  T   Rice    Truck
89  55  G   Corn    Train
92  93  S   Peas    Ship

哪一方做同样的事情,但可能有点难以理解。

答案 1 :(得分:1)

在循环播放之前,确实没有必要将所有行读入@temp。只读取第一行获取标题然后循环通过剩余的行立即打印它们会更有效:

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

my @temp;

my $line = <DATA>;
chomp($line);
my @head = split "\t", $line;

foreach $line (<DATA>) {
    chomp($line);
    my @elements = split ("\t", $line);
    foreach my $i (0..$#head) {
        print $head[$i], "\t", $elements[$i], "\n";
    }
    print "\n";
}

__DATA__
Year    Tonn    Class   Cargo   Type
88  61  T   Rice    Truck
89  55  G   Corn    Train
92  93  S   Peas    Ship

print行也可以写成:

print "$head[$i]\t$elements[$i]\n";

我只是觉得把所有部分分开来更清楚一点。