perl shuffle String and Array

I wrote a little script in Perl to shuffle Arrays or strings:

sub myshuffle {
    my @str = ($#_ == 0)?split(//o, $_[0]):@_;
    my $r1 = 0;
    my $r2 = 0;
    
    for(0..($#str*2)){
        $r1 = int(rand($#str+1));
        $r2 = int(rand($#str+1))while($r1 == $r2 && $#str>4);
        ($str[$r1],$str[$r2]) = ($str[$r2],$str[$r1]);
    }
    return join '', @str;
}

This are my examples:

print myshuffle("abcdefghijklmonopqrs").$/;
print myshuffle(1,2,3,4).$/;
print myshuffle(1,2,3).$/;
print myshuffle(1,2).$/;

and we got his as result:

obrdekohnlicgsfqapjm  
2431 
231 
21

One thought on “perl shuffle String and Array”

  1. Very good information. Lucky me I found your internet site by chance (stumbleupon).
    I actually have book-marked it for later!

Leave a Reply

Your email address will not be published.

1 × 3 =