Dave's Brain

Browse - programming tips - perl shuffle an array

Date: 2009dec27
Language: perl

Q.  How can I shuffle (randomize) an array in perl?

A.  Here's a function that does it:

	sub fisher_yates_shuffle($)
	{
		my $array = shift;
		my $i;
	
		for ($i = @$array; --$i; )
		{
			my $j = int rand($i+1);
			next if $i == $j;
			@$array[$i,$j] = @$array[$j,$i];
		}
	}
	
	sub example_use()
	{
		my(@a) = qw(aaa bbb ccc ddd);
	
		fisher_yates_shuffle(\@a);
		
	}

Source: perl cookbook
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.