Break your code up into subroutines. This will enable you to look at a logically related block of code at one time, demonstrate its correctness, and ultimately determine why it works on one record, but fails when it's executed twice.
Consider replacing this construction
if ($vat eq 1){$hasvat = "Yes"} else {$hasvat = "No"};