in reply to getting a while loop to terminate
It's because you have set $flag to '0', which is an uninterpolated string containing the character '0', a true value.
Instead, you should set $flag to zero, (0), without the single quotes. This will evaluate to false and make your logic all happy.
What can be asserted without proof can be dismissed without proof. - Christopher Hitchens, 1949-2011
In Section
Seekers of Perl Wisdom