line |
stmt |
bran |
cond |
sub |
pod |
time |
code |
1
|
|
|
|
|
|
|
package TablesRole::Util::Random; |
2
|
|
|
|
|
|
|
|
3
|
|
|
|
|
|
|
our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY |
4
|
|
|
|
|
|
|
our $DATE = '2020-11-04'; # DATE |
5
|
|
|
|
|
|
|
our $DIST = 'TablesRoles-Standard'; # DIST |
6
|
|
|
|
|
|
|
our $VERSION = '0.004'; # VERSION |
7
|
|
|
|
|
|
|
|
8
|
|
|
|
|
|
|
# enabled by Role::Tiny |
9
|
|
|
|
|
|
|
#use strict; |
10
|
|
|
|
|
|
|
#use warnings; |
11
|
|
|
|
|
|
|
|
12
|
1
|
|
|
1
|
|
541
|
use Role::Tiny; |
|
1
|
|
|
|
|
2
|
|
|
1
|
|
|
|
|
5
|
|
13
|
|
|
|
|
|
|
|
14
|
|
|
|
|
|
|
requires 'get_row_arrayref'; |
15
|
|
|
|
|
|
|
requires 'get_row_hashref'; |
16
|
|
|
|
|
|
|
|
17
|
|
|
|
|
|
|
sub _get_rand_rows { |
18
|
4
|
|
|
4
|
|
7
|
my ($self, $type, $num_items) = @_; |
19
|
4
|
|
|
|
|
7
|
my @items; |
20
|
4
|
|
|
|
|
5
|
my $i = -1; |
21
|
4
|
|
|
|
|
28
|
$self->reset_iterator; |
22
|
4
|
100
|
|
|
|
12
|
my $meth = $type eq 'arrayref' ? 'get_row_arrayref' : 'get_row_hashref'; |
23
|
4
|
|
|
|
|
20
|
while (defined(my $item = $self->$meth)) { |
24
|
20
|
|
|
|
|
22
|
$i++; |
25
|
20
|
100
|
|
|
|
37
|
if (@items < $num_items) { |
26
|
|
|
|
|
|
|
# we haven't reached $num_items, insert item to array in a random |
27
|
|
|
|
|
|
|
# position |
28
|
6
|
|
|
|
|
61
|
splice @items, rand(@items+1), 0, $item; |
29
|
|
|
|
|
|
|
} else { |
30
|
|
|
|
|
|
|
# we have reached $num_items, just replace an item randomly, using |
31
|
|
|
|
|
|
|
# algorithm from Learning Perl, slightly modified |
32
|
14
|
100
|
|
|
|
56
|
rand($i+1) < @items and splice @items, rand(@items), 1, $item; |
33
|
|
|
|
|
|
|
} |
34
|
|
|
|
|
|
|
} |
35
|
4
|
|
|
|
|
11
|
\@items; |
36
|
|
|
|
|
|
|
} |
37
|
|
|
|
|
|
|
|
38
|
|
|
|
|
|
|
sub get_rand_row_arrayref { |
39
|
1
|
|
|
1
|
1
|
2943
|
my $self = shift; |
40
|
1
|
|
|
|
|
15
|
my $rows = $self->get_rand_rows_arrayref(1); |
41
|
1
|
50
|
|
|
|
5
|
$rows ? $rows->[0] : undef; |
42
|
|
|
|
|
|
|
} |
43
|
|
|
|
|
|
|
|
44
|
|
|
|
|
|
|
sub get_rand_rows_arrayref { |
45
|
2
|
|
|
2
|
1
|
2107
|
my ($self, $n) = @_; |
46
|
2
|
|
|
|
|
6
|
$self->_get_rand_rows('arrayref', $n); |
47
|
|
|
|
|
|
|
} |
48
|
|
|
|
|
|
|
|
49
|
|
|
|
|
|
|
sub get_rand_row_hashref { |
50
|
1
|
|
|
1
|
1
|
2552
|
my $self = shift; |
51
|
1
|
|
|
|
|
5
|
my $rows = $self->get_rand_rows_hashref(1); |
52
|
1
|
50
|
|
|
|
4
|
$rows ? $rows->[0] : undef; |
53
|
|
|
|
|
|
|
} |
54
|
|
|
|
|
|
|
|
55
|
|
|
|
|
|
|
sub get_rand_rows_hashref { |
56
|
2
|
|
|
2
|
1
|
3078
|
my ($self, $n) = @_; |
57
|
2
|
|
|
|
|
5
|
$self->_get_rand_rows('hashref', $n); |
58
|
|
|
|
|
|
|
} |
59
|
|
|
|
|
|
|
|
60
|
|
|
|
|
|
|
1; |
61
|
|
|
|
|
|
|
# ABSTRACT: Provide utility methods related to getting random rows |
62
|
|
|
|
|
|
|
|
63
|
|
|
|
|
|
|
__END__ |