perl语言长宽数据转换(宽 -> 长 )

首先输入的文件类似如下图 为了转换为长数据,编写如下perl代码

#!/usr/bin/perl -w
use strict;
use warnings;
use Data::Dumper;

my $file=$ARGV[0];
my @matrix=();
my @month=();
my @year=();

open(RF,$file) || die $!;
open(WF,">tidy_data.txt") || die $!;

my $i=0;
while (my $line=<RF>){
    next if ($.==1);
    chomp($line);
    my @arr=split('\t',$line);
    shift(@arr);
    for my $j (0..@arr-1){
        $matrix[$i][$j]=$arr[$j];
    }
    $i++;
}
close(RF);

open(RF,$file) || die $!;
open(WFF,">process.txt") || die $!;

while(my $line=<RF>){
    if ($.==1){
        chomp($line);
        @month=split('\t',$line);
        next;
    }
    chomp($line);
    my @arr=split('\t',$line);
    print WFF $arr[0],"\n";
}
close(RF);
close(WFF);

open(RFF,"process.txt") || die $!;
while(my $line=<RFF>){
    chomp($line);
    push @year,$line;
}
close(RFF);

for my $i (0..$#year){
    for my $j (0..$#month){
        print WF $year[$i],"\t",$month[$j],"\t",$matrix[$i][$j],"\n";
    }
}

close(WF);
system("del process.txt")

便可实现转换,结果如下图

此条目发表在Perl分类目录。将固定链接加入收藏夹。

发表评论

邮箱地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud