perladdicted has asked for the wisdom of the Perl Monks concerning the following question:

i have two files,trying to see if the values of the files are not same than interchange the values.
#!/usr/bin/perl open FH, "master.cfg" or die $!; open FH1, "config1.cfg" or die $!; while(my $line=<FH>){ chomp; my %hash; (my $key,my $value) = split /=/, $line; $hash{$key} = $value; while(my $line2=<FH1>){ chomp; my %hash1; (my $key1,my $value1) = split /=/, $line; $hash1{$key} = $value; open FH1, ">config1_new.cfg" or die $!; if ($value1 != $value)
==============
[root@localhost test]# cat master.cfg env=qa env_var2=val2 env_var1=val1 env_var3=val3 env_var4=val4 env_var5=val5 [root@localhost test]# cat config1.cfg env_var3=x env_var4=y Var=conf
OUTPUT:
variavle=value env_var2=val2 env_var1=val1

Replies are listed 'Best First'.
Re: if value not matches replace it with other value
by pme (Monsignor) on Dec 30, 2014 at 08:56 UTC
    Hi perladdicted,

    Please enclose your code with <code> and </code> tags for better readability.

    The code below basically does what you need. You can change the if and print statements in according to your needs.

    #!/usr/bin/perl my %hash; open FH, "master.cfg" or die $!; while (<FH>) { chomp; my ($k, $v) = split /=/; $hash{$k} = $v; } close FH; open FH1, "config1.cfg" or die $!; while (<FH1>) { chomp; my ($key1, $value1) = split /=/; if ( defined $hash{$key1} and $hash{$key1} ne $value1) { print "$key1=$value1\n"; } } close FH1;
      Please note that your syntax for opening files works, but is somewhat obsolete. It is better to use the three-argument syntax and to use lexical filehandles. Something like this:
      my $infile = "master.cfg"; open my $FH, "<", $infile or die "could not open $infile $!";
      You of course have to adapt other places of your code where you use the filehandles (to use $FH instead of FH).