File Coverage

blib/lib/Array/Sample/SysRand.pm
Criterion Covered Total %
statement 22 22 100.0
branch 6 6 100.0
condition 5 5 100.0
subroutine 5 5 100.0
pod 1 1 100.0
total 39 39 100.0


line stmt bran cond sub pod time code
1             package Array::Sample::SysRand;
2              
3 1     1   54582 use 5.010001;
  1         12  
4 1     1   5 use strict;
  1         1  
  1         26  
5 1     1   5 use warnings;
  1         1  
  1         31  
6              
7 1     1   5 use Exporter qw(import);
  1         1  
  1         177  
8              
9             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
10             our $DATE = '2022-05-20'; # DATE
11             our $DIST = 'Array-Sample-SysRand'; # DIST
12             our $VERSION = '0.002'; # VERSION
13              
14             our @EXPORT_OK = qw(sample_sysrand);
15              
16             sub sample_sysrand {
17 44     44 1 7178 my ($ary, $n, $opts) = @_;
18 44   100     115 $opts //= {};
19              
20 44 100 100     123 return () if $n < 1 || @$ary < 1;
21              
22 41         58 my $k = @$ary / $n;
23 41         91 my $idx = rand() * @$ary;
24              
25 41         48 my @res;
26 41         60 for my $i (1..$n) {
27 61 100       113 push @res, $opts->{pos} ? int($idx) : $ary->[int($idx)];
28 61         66 $idx += $k;
29 61 100       115 $idx -= @$ary if $idx >= @$ary;
30             }
31              
32 41         83 @res;
33             }
34              
35             1;
36             # ABSTRACT: Systematic random sampling from an array
37              
38             __END__