use strict; use warnings; ## How many elements to pick use constant N => 10; ## The original array that must not be altered my @letters = ('a'..'z'); ##-----------------------------------------------------+ ## Generate code that will pick an element from ## @letters at each iteration without repeating ##-----------------------------------------------------+ my $picker_of_next_rand = gen_picker( \@letters ); ## Now execute (iterate) that code N times for (1..N) { print $picker_of_next_rand->(); } print "\n"; ## look nice print @letters, "\n"; ## original untouched exit( 0 ); ##-----------------------------------------------------+ ## This sub generates and returns code that will pick ## a random element from @$aref at each iteration ## without repeating ##-----------------------------------------------------+ sub gen_picker { my ($aref) = @_; my @indices = 0 .. $#$aref; ## closes on @indices return sub { if (! @indices) { die "No more items left to pick from"; } ##---------------------------------------------+ ## pick an int in the range (0 .. $#$aref), ## the range of the array's indices ##---------------------------------------------+ my $random_index = int rand @indices; ## $pick is the element at the random_index my $pick = $aref->[ $indices[ $random_index ] ]; ##---------------------------------------------+ ## We are about to pop the index array. Save ## the element at the pop-end of the index array ## by copying it into the position of the $pick ## (clobber index of $pick, won't be used again) ##---------------------------------------------+ $indices[ $random_index ] = $indices[ -1 ]; ## Now it is safe to pop the index array pop @indices; return $pick; }; } #### vkdbfymxie abcdefghijklmnopqrstuvwxyz