3

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
----------        -----     --------------
A                 rice      truck
B                 rice      truck
C                 rice      truck
D                 rice      truck
.............     .....     .........
N                 wheat     air cargo

Could anyone help. Thank you very much.

Gabriel Ščerbák
  • 16,864
  • 8
  • 33
  • 50
Nguyen
  • 49
  • 1
  • 3

3 Answers3

2

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! :)

daxim
  • 38,078
  • 4
  • 57
  • 123
Gabriel Ščerbák
  • 16,864
  • 8
  • 33
  • 50
1

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
daxim
  • 38,078
  • 4
  • 57
  • 123
Nguyen
  • 49
  • 1
  • 3
  • To handle the fixed-length records without having to add a `,` at the end, try using the [unpack](http://perldoc.perl.org/functions/unpack.html) function. See also [perlpacktut](http://perldoc.perl.org/perlpacktut.html#Packing-Text). Alternatively you could use [Parse::FixedLength](http://stackoverflow.com/questions/407407/how-do-i-read-fixed-length-records-in-perl). – stevenl Aug 03 '11 at 04:45
0

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

Data::Pivot

bvr
  • 9,599
  • 20
  • 28
Deleted
  • 4,368
  • 1
  • 18
  • 17