Text file compare output not in order

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • surwasesonal
    New Member
    • Apr 2013
    • 4

    Text file compare output not in order

    Hi All,
    I am quite new to perl , I want to compare two text files , and output should the unique values in each files.
    Using hash I am able to get unique values from each files but the output is not in order.
    what should I do to get output in order ?
    Code:
    use warnings;
    
    @ARGV == 2 or die "Must specify 2 files!\n";
    my $afile = shift;
    my $bfile = shift;
    
    my $ahash = make_hash($afile);
    my $bhash = make_hash($bfile);
    
    sub make_hash {
      my $file = shift;
      my %hash = ();
      open IN, "<$file" or die "Can't open '$file': $!\n";
      while (<IN>) {
        chomp;
        my ($key,$val) = split(/,/,$_);
        $hash{$key} = $val;
      }
      return \%hash;
    }
    
    print "In A hash but not B hash:\n",
    map {"$_\n"} grep {not exists $bhash->{$_}} keys %$ahash;
    
    print "In B hash but not A hash:\n",
    map {"$_\n"} grep {not exists $ahash->{$_}} keys %$bhash;
    I am getting output as follows :-
    In A hash but not B hash:
    abc
    abf
    abcdef
    In B hash but not A hash:
    abf2
    abcdef9
    abco


    I am expecting output as below,

    In A hash but not B hash:
    abc
    abcdef
    abf

    In B hash but not A hash:
    abco
    abcdef9
    abf2
    Last edited by surwasesonal; Apr 17 '13, 09:22 AM. Reason: adding output
  • surwasesonal
    New Member
    • Apr 2013
    • 4

    #2
    a.txt
    abc
    abcd
    abcdef
    hkdfg
    abf
    mklek


    b.txt
    abco
    abcd
    abcdef9
    hkdfg
    abf2
    mklek

    I am getting output as below,

    In A hash but not B hash:
    abc
    abf
    abcdef
    In B hash but not A hash:
    abf2
    abcdef9
    abco

    Comment

    • surwasesonal
      New Member
      • Apr 2013
      • 4

      #3
      I expect output as following
      In A hash but not B hash:
      abc
      abcdef
      abf

      In B hash but not A hash:
      abco
      abcdef9
      abf2

      Comment

      • RonB
        Recognized Expert Contributor
        • Jun 2009
        • 589

        #4
        Try adding sort to the map statement.
        map {"$_\n"} grep {not exists $bhash->{$_}} sort keys %$ahash;
        If that doesn't output it in the desired order, then you'll need to add a sub or block defining the sort routine.

        perldoc -f sort

        Comment

        • surwasesonal
          New Member
          • Apr 2013
          • 4

          #5
          Thanks RonB
          map {"$_\n"} grep {not exists $bhash->{$_}} sort keys %$ahash;

          this worked :)

          Comment

          Working...