#!/usr/bin/perl
package merger;
use strict;
#use sortfile;
Main();
sub Main {
my @aFilename = ();
if(scalar(@ARGV) < 1){
print "Please enter filenames\n";
my $sFilein = <>; chop($sFilein);
@aFilename = split(' ',$sFilein);
}
else { @aFilename = @ARGV; }
print "Filenames given = @aFilename \n";
if(scalar(@aFilename)%2){
die "Number of filename given must be %2 \n";
}
my $rarhDesc = GetAllDesc(\@aFilename);
MergeAll($rarhDesc,\@aFilename);
print "End Merger\n";
}
sub GetAllDesc { my $raFilename = shift;
print "Entering GetAllDesc\n";
my @aFilename = @$raFilename;
my @arhDesc = (); #array of reference hash (arh)
foreach my $sFile (@aFilename){
my $rhDesc = GetDesc($sFile);
print "rhDesc = $rhDesc\n";
push(@arhDesc,$rhDesc);
}
return \@arhDesc;
}
sub GetDesc { my $sFile = shift;
print "Entering GetDesc for $sFile \n";
my %hDesc;
unless(-r "$sFile"){ print "Can't read/found $sFile\n"; next; }
open FILEHANDLE,"$sFile" or next;
my $sID;
my $sTest;
foreach(<FILEHANDLE>){
if($_ =~ /#/){
# $sTest++;
$sID = $_; chomp($sID);
$sID =~ s/\#//g; #remove # from string
next if(length($sID)<2); #empty string
$hDesc{$sID} = "";
# die if($sTest >3);
# print "my id = $sID \n";
}
else { $hDesc{$sID} .= $_; }
}
# Printhash(\%hDesc,0); #display result
return \%hDesc;
}
sub MergeAll { my ($rarhDesc,$rafilename) = @_;
print "Entering MergeAll with $rarhDesc $rafilename\n";
my @arhDesc = @$rarhDesc; #tab of rhdesc
my @afilename = @$rafilename;
# print "arhDesc = [ @arhDesc ] \n";
# print "afilename = [ @afilename ] \n";
my $sI = 0;
for($sI=0; $sI < scalar(@arhDesc); $sI+=2){
# print "arhDesc => $arhDesc[$sI] $arhDesc[$sI+1] \n";
my $rhMergedHash = MergeHash($arhDesc[$sI],$arhDesc[$sI+1]); #need 2 rh as parameter
printMergedFile($rhMergedHash,$afilename[$sI]);
}
}
#verifie que toute les clé de hash2 soit dans hash1
sub MergeHash { my($rhHash1,$rhHash2) = @_;
print "Merging hashs = $rhHash1 : $rhHash2 \n";
my %hMergedHash = %$rhHash1;
foreach my $sKey2 (keys(%$rhHash2)){
unless($$rhHash1{$sKey2}) { #if exist and have value
$hMergedHash{$sKey2} = $$rhHash2{$sKey2};
}
}
return \%hMergedHash;
}
sub Printhash { my ($rhHash,$sIndent) = @_;
# print "My rhhash = $rhHash \n";
foreach my $sKey (keys(%$rhHash)){
my $sValue = $$rhHash{$sKey};
print "\t"x$sIndent." keys = ".$sKey."\n";
print "\t"x$sIndent." values=".$sValue."\n";
}
}
sub printMergedFile { my ($rhMergedHash,$sFile) = @_;
# print "My rhhash = $rhMergedHash file = $sFile\n";
my $sMergedFilename = "$sFile.merged";
# Printhash($rhMergedHash,-1);
# die;
unless(open FILEHANDLE,">$sMergedFilename"){
print "Can't writte $sMergedFilename\n";
return;
}
my @aSortedKey = sort keys(%$rhMergedHash);
foreach my $sKey (@aSortedKey){
my $sValue = $$rhMergedHash{$sKey};
print FILEHANDLE $sKey."#\n";
print FILEHANDLE $sValue."#\n";
}
}
1;