# code not tested because I've not got perl available # and I renamed your variables while ( $str =~ tr{a}{} # count the 'a's in $str && $count_y < $min_y # do we still want more 'y's? ) { # replace a random 'a' with a 'y' }