【问题标题】:Print header row and each row in file the file, side by side in columns打印标题行和文件中的每一行,并排在列中
【发布时间】:2016-04-01 19:10:06
【问题描述】:

您好,我有一个 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

【问题讨论】:

  • 不太清楚您要做什么。看起来你只是想读入内容并再次打印出来,我不明白你为什么要修改它们。您的预期输出示例会有所帮助

标签: perl


【解决方案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";

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

【讨论】:

    【解决方案2】:

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

    #!/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
    

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

    chomp ( my @header = split ( ' ', <DATA> ) ); 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 2020-06-09
      • 2021-08-16
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2015-03-06
      相关资源
      最近更新 更多