http://qs321.pair.com?node_id=210401


in reply to random elements from array - new twist

The solution provided by BrowserUK above is right on the money and is particularly good if the preservation of the original array set is important. If however this is not important and larger array sets are being manipulated, the following example using splice should prove to be more efficient.

sub pick (\@) { my $array = shift; return splice @{$array}, rand @{$array}, 1; } my @array = (1..15); my @results = (); push @results, pick @array for 1..5;

This code differs from the other solution above in that it makes use of the splice function to remove and return an element from the array, thereby ensuring that when the pick function is called again, that same value cannot be returned.

 

perl -e 'print+unpack("N",pack("B32","00000000000000000000000111011001")),"\n"'