Philip Potter wrote:
2009/11/3 John W. Krahn <jwkr...@shaw.ca>:
Majian wrote:
my @array = ('uriel', 'daniel', 'joel', 'samuel');

Now what I want is create a process so every time I print the array it
prints  one element from the array .

I wrote it like this :

#!/usr/bin/perl -w

use strict;
use List::Util 'shuffle';


my @array = ('uriel', 'daniel', 'joel', 'samuel');
print "Array before random: @array\n\n";

print "Array of random: $array[rand @array]\n";
@array = shuffle @array;

print "Array of random: @array\n\n";

That doesn't pick one random element from the array. That shuffles the
whole array.

From the OP's original message:

"I want to know if there is a way in which I can randomnize(?) the content in an array."

And then he goes on to say:

"Now what I want is create a process so every time I print the array it prints one element from the array."

Which he does correctly so I assumed that he didn't know how to do the first part and thus the use of List::Util::shuffle().


I feel it's probably worth saying here that shuffling an array is an
easy thing to get wrong -- ie if you try to roll your own subroutine
its easy to accidentally make some permutations more likely than
others.

Yes, this has been discussed in depth on c.l.p.m, particularly in relation to the FAQ:

perldoc -q "How do I shuffle an array randomly"


One example of how it can look right but not be right:

sub badshuffle {
    my @array = @_
    for my $i (0..$#array) {
        # For each element, randomly swap it with another element
        my $rand = rand @array;
        ($array[$i], $array[$rand]) = ($array[$rand], $array[$i]);

In Perl that is usually written as:

          @array[ $i, $rand ] = @array[ $rand, $i ];


    }

Since you are making a copy of the contents of @_ into the array @array you must then return those contents.

      return @array;


}


John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to