in reply to Merge the difference between two files and save it on the first file. Also update the first file with info in second file.

#./script.pl file1 file2
%hash = map {$_ => 1} <>; open OUT, '> file3' or die $!; print OUT for (sort keys %hash);
i wouldn't change the original file1
hence file3 as output
  • Comment on Re: Merge the difference between two files and save it on the first file. Also update the first file with info in second file.
  • Download Code

Replies are listed 'Best First'.
Re^2: Merge the difference between two files and save it on the first file. Also update the first file with info in second file.
by Corion (Patriarch) on Oct 11, 2013 at 07:44 UTC

    This is wrong. For example for the two given input files, your code gives the following output:

    %hash = map {$_ => 1} <DATA>; print for (sort keys %hash); __DATA__ A=hello B=world B=planet C=universe
    Output:
    A=hello B=planet B=world C=universe

    ... but the expected output is

    A=hello B=planet C=universe

    The input data is basically a two-column input and the keys are in the first column. The hash approach in general is correct, but you need to use the stuff left of the equal sign as key and the rest (or the whole line) as value:

    use strict; my %hash = map {/^(.*)=/ or die "Malformed input: $_"; $1 => $_} <DATA +>; print for (sort values %hash); __DATA__ A=hello B=world B=planet C=universe
      when I wrote that, the author didnt clarify
      the tasks clearly yet
      if he needs select the name before "="
      i would go with code:
      %hash = map {/=(\w+)/; $` => $1} <DATA>; foreach (sort keys %hash){ print "$_ $hash{$_}\n"; } __DATA__ A=hello B=world B=planet C=universe