$r is the same thing as $rand so it should have worked and you should have updated your old code instead of posting a new snippet
you also have a bracket mismatch, line 3 needs a { at the end
this could also be shortened alot by using $str