Vertical an horizontal pivoing in unix

Please help me to do Vertical an horizontal pivoing in unix in single run.
The input file is like this-

MRKT|PROD|PRD|FACT1|FACT2|FACT3|FACT4
M1|P1|PR1|F11|F12|F13|F14
M1|P1|PR2|F21|F22|F23|F24
M1|P1|PR3|F31|F32|F33|F34
M2|P2|PR1|F41|F42|F43|F44
M2|P2|PR2|F51|F53|F54|F55
M2|P2|PR3|F61|F64|F65|F66

and output file is like this-

MRKT|PROD|FACT|PR1|PR2|PR3
M1|P1|FACT1|F11|F21|F31
M1|P1|FACT2|F12|F22|F32
M1|P1|FACT3|F13|F23|F33
M1|P1|FACT4|F14|F24|F34
M2|P2|FACT1|F41|F51|F61
M2|P2|FACT2|F42|F52|F62
M2|P2|FACT3|F43|F53|F63
M2|P2|FACT4|F44|F54|F64

Please describe the relationship between the two files; i.e. describe what is done to the first to get the second.

#!/usr/bin/perl
use strict;
my (%hash,%h);
print "MRKT|PROD|FACT|PR1|PR2|PR3\n";
open FH,"<a.txt" or die "Can not open file";
while(<FH>){
	chomp;
	my @tmp=split("[|]",$_);
	my $key=$tmp[0]."|".$tmp[1];
	for(my $i=3;$i<=$#tmp;$i++){
		if($. == 1){
			$h{$i}=$tmp[$i];
		}
		else{
			$hash{$key}->{$h{$i}}.="|".$tmp[$i];
		}
	}
}
close FH;
for my $key (sort keys %hash){
	my %tmp=%{$hash{$key}};
	for my $k (sort keys %tmp){
		print $key,"|",$k,$tmp{$k},"\n";
	}
}

Thanks Cherry this helps but I have one more complication that ....there may be data like this -- (FOr few key values periods may differ and facts as well)

MRKT|PROD|PRD|FACT1|FACT2|FACT3|FACT4
M1|P1|PR1|F11|F12|F13|F14
M1|P1|PR3|F31|F32|F33|F34
M2|P2|PR1|F41|F42|F43|F44
M2|P2|PR2|F51|F53|F54|F55
M2|P2|PR3|F61|F64|F65|F66
M3|P3|PR3|F71|F72|

and important thing that fact columns may be variable as well...It is possible to address this using perl

Hey Johnson. Here I am trying to do pivoting of the data. We have Market and Product for which we have variable number of facts and Period.
In input data key is made of markt,product and period and value is fact values but we need to do a pivoting so that key will be market,product and fact and value will be a period value.