Scramble a string.

Hi all,

I am trying to write a perl script that will take user input as a string and scramble the string and print the result.
Note: I cannot use shuffle function ....using for loop.

so here is example.
Enter a String: abcdef

Print the Result: debacf 

Enter a String: abcdef

print the Result: cdabef

Here is my perl code but it doesn't work exactly:

print "Enter a string:   ";
$sString = <STDIN>;

chomp($sString);

print "String = $sString\n";

$iLength = length($sString);
@array = split(//, $sString);

print "array = @array\n";

print "length = $iLength\n";
for ( $i = 1; $i <= $iLength; $i++ ){
$item = int(rand($#array));
print "@array[$item]\n";
}

Please any body help me.

thanks,

If you have perl 5.8.0 or later your should have shuffle. If you cannot use shuffle, why not?

The simplest way is to loop through the array swapping each item with another item in a random position. Note that the array is indexed from 0, not 1.

for ( $i = 0; $i < $iLength; $i++ ){
        $random = int(rand($#array));
        $temp=$array[$random];
        $array[$random]=$array[$i];
        $array[$i]=$temp;
}
for ( $i = 0; $i < $iLength; $i++ ){
        print "$array[$i]";
}
print "\n";

I hadn't heard of shuffle so I googled a bit.

perlfaq4 - perldoc.perl.org