开发者

help parsing tab file and custom formatting in perl

I have an output file that is \t delimited:

Data for 08/10/2011 
Host    QueueName   Queue-id    
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130

I'm looking to remove the first line (date) and then I want the 2nd line (header columns) to print out with th开发者_JS百科e values like so as my final output file:

Host=test QueueName=123 Test Q Queue-id=110
Host=test QueueName=456 Test Q Queue-id=120
Host=test QueueName=789 Test Q Queue-id=130

What is a good way/practice to do this in perl?


I would recommend Text::CSV_XS for reading the file.

In this recent question, there was a similar problem: How can I use Perl extract a particular column from a tab-separated file? (See my answer)

use warnings;
use strict;
use Text::CSV_XS;
use autodie;

my $csv = Text::CSV_XS->new( { sep_char => "\t" } );
<DATA>;  # discard the first line
$csv->column_names ($csv->getline (*DATA));
my $hr = $csv->getline_hr_all(*DATA); 

for my $hashref (@$hr) {
    my @list;
    for my $key ($csv->column_names()) {
        push @list, join '=', $key, $hashref->{$key};
    }
    print "@list\n";
}
__DATA__
Data for 08/10/2011 
Host    QueueName   Queue-id    
test    123 Test Q  110
test    456 Test Q  120
test    789 Test Q  130
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜