in reply to the variable is lost

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

and $_ is aliased to $a and $b in turn by the foreach loop. Every time you change $_ by assigning a line to it, you change the value of $a or $b.

Solution: Change

while(<$fh>){ print; }

to

local $_; while(<$fh>){ print; }

or

while(my $line = <$fh>){ print $line; }

By the way, because $a and $b have special meaning to sort, one usually avoids them. my $a and my $b can actually cause sort to malfunction.