The problem you are having is that hashes are not kept
in any particular order. It was lucky that
you happened to get values out of the hash
in the alphabetical order
file #1. But, because of the nature of hash tables,
this is quite often not true.
To fix your problem you can use a
foreach my $k (sort keys %GRAMMAR)
instead of your while loop assuming you want
alphabetical order.