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   53371 use 5.010001;
  1         11  
4 1     1   5 use strict;
  1         1  
  1         18  
5 1     1   3 use warnings;
  1         2  
  1         30  
6              
7 1     1   5 use Exporter qw(import);
  1         1  
  1         180  
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.003'; # VERSION
13              
14             our @EXPORT_OK = qw(sample_sysrand);
15              
16             sub sample_sysrand {
17 44     44 1 7384 my ($ary, $n, $opts) = @_;
18 44   100     120 $opts //= {};
19              
20 44 100 100     160 return () if $n < 1 || @$ary < 1;
21              
22 41         60 my $k = @$ary / $n;
23 41         88 my $idx = rand() * @$ary;
24              
25 41         58 my @res;
26 41         59 for my $i (1..$n) {
27 61 100       118 push @res, $opts->{pos} ? int($idx) : $ary->[int($idx)];
28 61         70 $idx += $k;
29 61 100       119 $idx -= @$ary if $idx >= @$ary;
30             }
31              
32 41         88 @res;
33             }
34              
35             1;
36             # ABSTRACT: Systematic random sampling from an array
37              
38             __END__