Another variation that's useful if the elements of the array itself are large and therefore costly to shuffle or perhaps more importantly, if its necessary to keep the array in it's original order.
Instead of shuffling the array, create and shuffle an array of indexes, then subset it to produce a slice from the real array.
#! perl -sw
use strict;
sub shufl (\@) { my $r=pop; $a = $_ + rand @{$r} - $_ and @$r[$_, $a]
+= @$r[$a, $_] for (0..$#{$r}); }
my @array = qw(the quick brown fox jumps over the lazy dog and went st
+raight into a puddle);
my @indexes = (0..$#array);
shufl(@indexes);
my ($comp1, $comp2, $comp3, $comp4, $comp5) = @array[@indexes[0..4]];
print"$comp1, $comp2, $comp3, $comp4, $comp5\n";
__END__
#Ouput
C:\test>210389.pl
jumps, dog, a, the, fox
C:\test>210389.pl
a, the, lazy, brown, into
C:\test>210389.pl
and, quick, a, puddle, fox
C:\test>210389.pl
a, and, the, the, into
C:\test>210389.pl
dog, jumps, went, the, straight
C:\test>210389.pl
lazy, quick, and, into, fox
C:\test>210389.pl
the, went, the, brown, over
C:\test>
Nah! Your thinking of Simon Templar, originally played by Roger Moore and later by Ian Ogilvy
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.