# Assumes each cat1 appears only once in file2. my %cat2_by_cat1; while (<$fh2>) { chomp; my ($cat1, $cat2) = split /=/; $cat2_by_cat1{$cat1} = $cat2; } while (<$fh1>) { chomp; my ($dog, $bird, $cat1) = split /=/; exists( $cat2_by_cat1{$cat1} ) or die; my $cat2 = $cat2_by_cat1{$cat1}; print $fh_out (join('=', $dog, $bird, $cat1, $cat2), "\n"); }