开发者

Transpose rows into columns using Perl

开发者 https://www.devze.com 2023-03-24 04:59 出处:网络
I am newbie with Perl. I have an assignment to transpose rows into columns of a huge data. customersgoodstransportation

I am newbie with Perl. I have an assignment to transpose rows into columns of a huge data.

customers         goods     transportation
----------        -----     --------------
A, B, C, D        rice      truck
E, G, D           corn      train
.............     .....     .........
T, H, K, M, N     wheat     air cargo

And I would like to have an output look like:

customers         goods     transportation
----------        -----     --------------开发者_Go百科
A                 rice      truck
B                 rice      truck
C                 rice      truck
D                 rice      truck
.............     .....     .........
N                 wheat     air cargo

Could anyone help. Thank you very much.


Most probably you have come across the map function, study how it works and how you construct rows or columns and you will get it, good luck! :)


Thank you all. After few hours trying I could figure out how to do my assignment. It needs some simple steps of manually intervention for the input and output, i.e. add an , at the end of the first column of the input and remove \ in the second column of the output using Excel. It is time to submit the output. I appreciate if someone has a better Perl code to solve it.

#!/usr/bin/perl
my @records;
while (<DATA>) {
    chomp;
    my @columns = split ", ", $_;
    push @records, \@columns;
}

foreach my $record (@records) {
    foreach my $column (@{$record}) {
        if (\$column != \$$record[-1]) {
            print "$column\t \\$$record[-1]\n";
        }
    }
}

__DATA__
A, B, C, D,     Rice    Truck
E, G, D,    Corn    Train
T, H, K, M, N,  Wheat   Air cargo

__OUTPUT__
A    \  Rice    Truck
B    \  Rice    Truck
C    \  Rice    Truck
D    \  Rice    Truck
E    \  Corn    Train
G    \  Corn    Train
D    \  Corn    Train
T    \  Wheat   Air cargo
H    \  Wheat   Air cargo
K    \  Wheat   Air cargo
M    \  Wheat   Air cargo
N    \  Wheat   Air cargo


It's a long time since I looked at perl, but is this perl mod any good?

Data::Pivot

0

精彩评论

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