in reply to Search, Match, Compare, and Report

sub load { my ($qfn) = @_; open(my $fh, '<', $qfn) or die("Can't open file \"$qfn\": $!\n"); my %data; local *_; while (<$fh>) { my ($id) = /^(\S+)/ or next; die("Duplicate key $id\n") if exists($data{$id}); $data{$id} = $_; } return \%data; } my $master = eval { load(...) } or die("Can't load master db: $@"); my $new = eval { load(...) } or die("Can't load new db: $@"); my %ids; for my $id (keys(%$master), keys(%$new)) { next if $ids{$id}++; if (!exists($new->{$id})) { print("-$master->{$id}"); } elsif (!exists($master->{$id})) { print("+$new->{$id}"); } elsif ($master->{$id} ne $new->{$id}) { print("-$master->{$id}"); print("+$new->{$id}"); } else { print("=$master->{$id}"); } }

Update: Added missing parens and fixed var name as per reply.

Replies are listed 'Best First'.
Re^2: Search, Match, Compare, and Report
by ahmad (Hermit) on Jan 31, 2010 at 23:24 UTC

    Looks interesting, what local *_; actually does in this code?

    BTW, There are few missing brackets & $keys{$id}++ meant to be $ids{$id}++ in your code right below the for loop.

      while (<...>)
      is short for
      while (defined($_ = <...>))

      local *_; prevents the clobbering of the parent's $_. my $_; would also do the trick in Perl 5.10+

        Thanks for clarifying

Re^2: Search, Match, Compare, and Report
by kirkbrown (Novice) on Feb 02, 2010 at 03:02 UTC
    Thank you very much Monks! Another question, If I have two .txt files, how do I pass the files into the program? I'm new to Perl and programming.
      Command line arguments are provided via @ARGV