I came across this same thing yesterday while trying to do a one-line append loop. I thought it was something to do with the my - possibly re-initialising on each loop?
Haven't got to the bottom of it yet and basically ended up doing like you have in the second example (declare the variable and then do the loop seperately).
All code is untested unless otherwise stated.
All opinions expressed are my own and are intended as guidance, not gospel; please treat what I say as such and as Abigail said Think for yourself.
If in doubt ask.