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

长数据如下图

perl代码如下

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

my $usage=<<USAGE;
Usage:
    perl $0 inputfile
USAGE
if(@ARGV==0){die $usage};

my $file=$ARGV[0];
my %timeinfo=();
my $reftime=\ %timeinfo;
my $i=0;

open(RF,$file) || die $!;
open(WF,">kuan_data.txt") || die $!;
while(my $line=<RF>){
    next if ($.==1);
    chomp($line);
    my @arr=split('\t',$line);
    $reftime -> {$arr[0]} -> {$arr[1]} =$arr[2];

}

for my $j (keys %{$reftime}){
    $i=0;
    for my $dd (keys %{$reftime -> {$j}}){
        $i++;
    }
}

for my $year (sort {$a cmp $b} keys %{$reftime}){ 
    my $j=1;
    for my $month (sort {$a <=> $b} keys %{$reftime -> {$year}}){  
        if ($j==1){
            print WF $month,"\t";
            $j++;
        }elsif($j<$i){
            print WF $month,"\t";
            $j++;
        }elsif($j==$i){
            print WF $month,"\n";
        }else{
            next;
        }
    }
    last;
}


for my $year (sort {$a cmp $b} keys %{$reftime}){
    my $j=1;
    for my $month (sort {$a <=> $b} keys %{$reftime -> {$year}}){
        if ($j==1){
            print WF $year,"\t",$reftime -> {$year} -> {$month},"\t";
            $j++;
        }elsif($j>0 && $j < $i){
            print WF $reftime -> {$year} -> {$month},"\t";
            $j++;
        }else{
            print WF $reftime -> {$year} -> {$month},"\n";
        }
    }
}

close(RF);
close(WF);

得到最后的宽数据,如下图

此条目发表在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