1#!./perl 2 3use strict; 4use warnings; 5 6use Test::More tests => 9; 7 8use List::Util qw(sample); 9 10{ 11 my @items = sample 3, 1 .. 10; 12 is( scalar @items, 3, 'returns correct count when plentiful' ); 13 14 @items = sample 10, 1 .. 10; 15 is( scalar @items, 10, 'returns correct count when exact' ); 16 17 @items = sample 20, 1 .. 10; 18 is( scalar @items, 10, 'returns correct count when short' ); 19} 20 21{ 22 my @items = sample 5, 1 .. 5; 23 is_deeply( [ sort { $a <=> $b } @items ], [ 1 .. 5 ], 24 'returns a permutation of the input list when exact' ); 25} 26 27{ 28 # These two seeds happen to give different results for me, but there is the 29 # smallest 1-in-2**48 chance that they happen to agree on some platform. If 30 # so then pick a different seed value. 31 32 srand 1234; 33 my $x = join "", sample 3, 'a'..'z'; 34 35 srand 5678; 36 my $y = join "", sample 3, 'a'..'z'; 37 38 isnt( $x, $y, 'returns different result on different random seed' ); 39 40 srand; 41} 42 43{ 44 my @nums = ( 1..5 ); 45 sample 5, @nums; 46 47 is_deeply( \@nums, [ 1..5 ], 48 'sample does not mutate passed array' 49 ); 50} 51 52{ 53 my $destroyed_count; 54 sub Guardian::DESTROY { $destroyed_count++ } 55 56 my @ret = sample 3, map { bless [], "Guardian" } 1 .. 10; 57 58 is( $destroyed_count, 7, 'the 7 unselected items were destroyed' ); 59 60 @ret = (); 61 62 is( $destroyed_count, 10, 'all the items were destroyed' ); 63} 64 65{ 66 local $List::Util::RAND = sub { 4/10 }; 67 68 is( 69 join( "", sample 5, 'A'..'Z' ), 70 join( "", sample 5, 'A'..'Z' ), 71 'rigged rand() yields predictable output' 72 ); 73} 74