开发者

Transposing Excel columns into rows based on id numbers using Perl

开发者 https://www.devze.com 2023-04-04 08:04 出处:网络
Hi I am fairly new to Perl and been asked to do a task. I have a record file in .csv format with 10 or more files and been asked to transpose the records so each row is turned into 10 rows per record

Hi I am fairly new to Perl and been asked to do a task.

I have a record file in .csv format with 10 or more files and been asked to transpose the records so each row is turned into 10 rows per records.

id Column1 column2 column3 ..... column N
1  apple   Red     Medium       开发者_如何学编程 Text1
2  Mango   Yellow  Large         Text2
3  Banana  Yellow  small         Text3
4  Apple   Red     Medium        Text4
5  Pear    Green   Medium        Text5

And this need to be displayed as

id 1 column1   Apple
id 1 column2   Red
id 1 column3   Medium
.
.
id 1 columnN   text1

Any help or suggestion is greatly appreciated.


As @aartist commented, all you need is Text::CSV. You can install it with cpan utility or with this oneliner:

curl -L http://cpanmin.us | perl - --sudo Text::CSV

Please read documentation, your task should be solved very easy.


Edit: Per additional input it looks like kind-of interleaved header columns are needed:

use Text::CSV_XS;

my $csv = Text::CSV_XS->new({ binary => 1, sep_char => ';' })
    or die;

my $hdr = $csv->getline(\*DATA);
while (my $row = $csv->getline(\*DATA)) {
    $csv->combine(
        map { $hdr->[0], $row->[0], $hdr->[$_], $row->[$_] } 1..$#$row
    );
    print $csv->string,"\n";
}

__DATA__
id;Column1;column2;column3;columnN
1;apple;Red;Medium;Text1
2;Mango;Yellow;Large;Text2
3;Banana;Yellow;small;Text3
4;Apple;Red;Medium;Text4
5;Pear;Green;Medium;Text5

This gives:

id;1;Column1;apple;id;1;column2;Red;id;1;column3;Medium;id;1;columnN;Text1
id;2;Column1;Mango;id;2;column2;Yellow;id;2;column3;Large;id;2;columnN;Text2
id;3;Column1;Banana;id;3;column2;Yellow;id;3;column3;small;id;3;columnN;Text3
id;4;Column1;Apple;id;4;column2;Red;id;4;column3;Medium;id;4;columnN;Text4
id;5;Column1;Pear;id;5;column2;Green;id;5;column3;Medium;id;5;columnN;Text5
0

精彩评论

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