One comment: In your first while loop, do you mean
while(<MESG>) rather than while()?
(As it stands, it doesn't seem like it can do anything.)
With that change it does run (but I haven't studied it enough to really understand what the point is.) You could explain what you're trying to do if you wish.
chas