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   68218 use 5.010001;
  1         12  
4 1     1   5 use strict;
  1         2  
  1         20  
5 1     1   4 use warnings;
  1         2  
  1         39  
6              
7 1     1   24 use Exporter qw(import);
  1         2  
  1         270  
8              
9             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
10             our $DATE = '2023-06-20'; # DATE
11             our $DIST = 'Array-Sample-SysRand'; # DIST
12             our $VERSION = '0.004'; # VERSION
13              
14             our @EXPORT_OK = qw(sample_sysrand);
15              
16             sub sample_sysrand {
17 44     44 1 8183 my ($ary, $n, $opts) = @_;
18 44   100     140 $opts //= {};
19              
20 44 100 100     192 return () if $n < 1 || @$ary < 1;
21              
22 41         85 my $k = @$ary / $n;
23 41         110 my $idx = rand() * @$ary;
24              
25 41         61 my @res;
26 41         74 for my $i (1..$n) {
27 61 100       131 push @res, $opts->{pos} ? int($idx) : $ary->[int($idx)];
28 61         91 $idx += $k;
29 61 100       139 $idx -= @$ary if $idx >= @$ary;
30             }
31              
32 41         106 @res;
33             }
34              
35             1;
36             # ABSTRACT: Systematic random sampling from an array
37              
38             __END__