I haven't fully investigated but it seems this is a weird bashism down to how sub shells are managed.
cat file | while read var ; do stuff ; done
The above piece of code opens a subshell due to the pipe. This subshell can have weird effects on variables. I know i'm not explaining this very well but essentially there is a way around the issue by using the following format;
while read var ; do stuff ; done < file
The above format removes the need for the extra subshell so should work as expected.
It took me AGES to work this out when I first met it.
If you re-factor your code to work in that way you should be able to get around the issue.
Of course there's no reason why Watael's suggestion should not work