... $aod[$yb] = rankdwn( $aod[$yb], $howManyYsDoWeWant ); ... sub rankdwn { my ( $str, $incrsdel ) = @_; my $cnd_y = $str =~ tr/y/y/; my @aPosns; push @aPosns, pos $str while $str =~ m{(?=a)}g; my @cPosns; push @cPosns, pos $str while $str =~ m{(?=c)}g; while ( ( $cnd_y < $incrsdel ) && @aPosns ) { my $offset = splice @aPosns, rand @aPosns, 1; substr $str, $offset, 1, q{y}; $cnd_y ++; } while ( ( $cnd_y < $incrsdel ) && @cPosns ) { my $offset = splice @cPosns, rand @cPosns, 1; substr $str, $offset, 1, q{y}; $cnd_y ++; } return $str; }