我有 A.ini 和 B.ini 这样的文件,我想合并 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
我希望用 perl 语言完成这个合并,并且我想将旧的 A.ini 文件的副本保存在其他地方以使用旧副本
答案1
#!/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);
答案2
#!/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;