=head1 NAME
-perlfaq4 - Data Manipulation ($Revision: 1.49 $, $Date: 1999/05/23 20:37:49 $)
+perlfaq4 - Data Manipulation ($Revision: 1.2 $, $Date: 2001/09/26 15:42:12 $)
=head1 DESCRIPTION
This has the strange effect of turning "C<don't do it>" into "C<Don'T
Do It>". Sometimes you might want this. Other times you might need a
-more thorough solution (Suggested by brian d. foy):
+more thorough solution (Suggested by brian d foy):
$string =~ s/ (
(^\w) #at the beginning of the line
=head2 How do I shuffle an array randomly?
-Use this:
+If you either have Perl 5.8.0 or later installed, or if you have
+Scalar-List-Utils 1.03 or later installed, you can say:
+
+ use List::Util 'shuffle';
+
+ @shuffled = shuffle(@list);
+
+If not, you can use this:
# fisher_yates_shuffle( \@array ) :
# generate a random permutation of @array in place
sub fisher_yates_shuffle {
my $array = shift;
- my $i;
- for ($i = @$array; --$i; ) {
+ my $i = @$array;
+ while (--$i) {
my $j = int rand ($i+1);
@$array[$i,$j] = @$array[$j,$i];
}
fisher_yates_shuffle( \@array ); # permutes @array in place
+Note that the above implementation shuffles an array in place,
+unlike the List::Util::shuffle() which takes a list and returns
+a new shuffled list.
+
You've probably seen shuffling algorithms that work using splice,
randomly picking another element to swap the current element with
module from CPAN runs at least an order of magnitude faster. If you don't
have a C compiler (or a binary distribution of Algorithm::Permute), then
you can use List::Permutor which is written in pure Perl, and is still
-several times faster than the toy algorithm above.
+several times faster than the algorithm above.
=head2 How do I sort an array by (anything)?