-1

I have to files like A.ini and B.ini ,I want to merge both the files in A.ini

examples of files:
A.ini::

a=123
b=xyx
c=434

B.ini contains:
a=abc
m=shank
n=paul

my output in files A.ini should be like

a=123abc
b=xyx
c=434
m=shank
n=paul

I want to this merging to be done in perl language and I want to keep the copy of old A.ini file at some other place to use old copy

  • If you have a non-working script, we have help improving it! – Khaled Apr 16 '12 at 10:20
  • @Khaled I am new to this perl scripting and I have to do this from scratch . – Ashish Sharma Apr 16 '12 at 10:23
  • 1
    I wanted to say you should try to do it yourself first. Just search for how to read and write files in Perl. Start with something simple and make it better. If you stuck, you can then ask. – Khaled Apr 16 '12 at 10:27
  • 1
    General programming questions should really be asked on [Stack Overflow](http://www.stackoverflow.com/faq) or [Programmers](http://programmers.stackexchange.com/faq). Questions that boil down to "Please give me the code" should not be asked at all (I don't know if that was your intent, but it's what wound up happening in the answers, and that's a pretty lousy way to learn a language) – voretaq7 Apr 16 '12 at 14:49

2 Answers2

3
#!/usr/bin/perl

use strict;
use warnings;
use File::Copy;

my $fileA = "a.ini";
my $fileB = "b.ini";
my ($name, $value, %hash);

open(my $fh, '<', $fileA) or die $!;
while(<$fh>)
{
    chomp $_;
    ($name, $value) =  split(/=/, $_);
    $hash{$name} = $value;
}
close($fh);

open($fh, '<', $fileB) or die $!;
while(<$fh>)
{
    chomp $_;
    ($name, $value) =  split(/=/, $_);
    if (exists $hash{$name})
    {
        $hash{$name} = $hash{$name} . $value;
    }
    else
    {
        $hash{$name} = $value;
    }
}
close($fh);

print "Renaming a.ini to old_a.ini\n";
move($fileA, "old_".$fileA) or die $!;

print "Result:\n\n";
open($fh, '>>', $fileA) or die $!;
foreach my $k (sort {$a cmp $b} keys %hash)
{
    print $fh "$k=$hash{$k}\n";
    print "$k: $hash{$k}\n";
}
close($fh);
Prix
  • 4,881
  • 3
  • 24
  • 25
0
#!/usr/bin/perl

use List::MoreUtils;


open my $f1 , '<' , $file1 || or die "...";
my @file1 = <$f1>;
close $f1;

open my $f2 , '<' , $file2 || or die "...";
my @file2 = <$f2>;
close $f2;

my @zip = zip @file1, @file2;

open my $a1 , ">" , $answrfile || die

 "...";
map { print $a1 $_ } @zip;
close $al;
cjc
  • 24,916
  • 3
  • 51
  • 70