Your code for opening files is not the best. Take a look at open.
$1 holds data you've captured with a regexp. See perlre.
If you follow the advice in the open documentation, you can write your while loops as while (my $line = <$file_handle>) { ... } which should solve your main problem.