in reply to using unless($code == 200)....

If you just want to skip the loop when $response == 500 you could try putting this at the beginning of your loop -
next if 500 == $response;
this should go to the next iteration of the loop if $response is equal to 500. If you're still having troubles, you'll probably want to check that $response actually reaches 500 as it may be getting lost somewhere along the line.
I'd also recommend using the CONSTANT == $VARIABLE coding style as it keeps your code safe from accidental conditional assignments (we don't want $response = 500!).
HTH

broquaint