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-10'; # DATE |
5
|
|
|
|
|
|
|
our $DIST = 'TablesRoles-Standard'; # DIST |
6
|
|
|
|
|
|
|
our $VERSION = '0.006'; # VERSION |
7
|
|
|
|
|
|
|
|
8
|
|
|
|
|
|
|
# enabled by Role::Tiny |
9
|
|
|
|
|
|
|
#use strict; |
10
|
|
|
|
|
|
|
#use warnings; |
11
|
|
|
|
|
|
|
|
12
|
1
|
|
|
1
|
|
611
|
use Role::Tiny; |
|
1
|
|
|
|
|
2
|
|
|
1
|
|
|
|
|
7
|
|
13
|
|
|
|
|
|
|
|
14
|
|
|
|
|
|
|
requires 'get_row_arrayref'; |
15
|
|
|
|
|
|
|
requires 'get_row_hashref'; |
16
|
|
|
|
|
|
|
|
17
|
|
|
|
|
|
|
sub _get_rand_rows { |
18
|
4
|
|
|
4
|
|
9
|
my ($self, $type, $num_items) = @_; |
19
|
4
|
|
|
|
|
8
|
my @items; |
20
|
4
|
|
|
|
|
5
|
my $i = -1; |
21
|
4
|
|
|
|
|
25
|
$self->reset_iterator; |
22
|
4
|
100
|
|
|
|
15
|
my $meth = $type eq 'arrayref' ? 'get_row_arrayref' : 'get_row_hashref'; |
23
|
4
|
|
|
|
|
21
|
while (defined(my $item = $self->$meth)) { |
24
|
20
|
|
|
|
|
33
|
$i++; |
25
|
20
|
100
|
|
|
|
40
|
if (@items < $num_items) { |
26
|
|
|
|
|
|
|
# we haven't reached $num_items, insert item to array in a random |
27
|
|
|
|
|
|
|
# position |
28
|
6
|
|
|
|
|
62
|
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
|
|
|
|
71
|
rand($i+1) < @items and splice @items, rand(@items), 1, $item; |
33
|
|
|
|
|
|
|
} |
34
|
|
|
|
|
|
|
} |
35
|
4
|
|
|
|
|
13
|
\@items; |
36
|
|
|
|
|
|
|
} |
37
|
|
|
|
|
|
|
|
38
|
|
|
|
|
|
|
sub get_rand_row_arrayref { |
39
|
1
|
|
|
1
|
1
|
1733
|
my $self = shift; |
40
|
1
|
|
|
|
|
12
|
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
|
2497
|
my ($self, $n) = @_; |
46
|
2
|
|
|
|
|
8
|
$self->_get_rand_rows('arrayref', $n); |
47
|
|
|
|
|
|
|
} |
48
|
|
|
|
|
|
|
|
49
|
|
|
|
|
|
|
sub get_rand_row_hashref { |
50
|
1
|
|
|
1
|
1
|
2826
|
my $self = shift; |
51
|
1
|
|
|
|
|
7
|
my $rows = $self->get_rand_rows_hashref(1); |
52
|
1
|
50
|
|
|
|
7
|
$rows ? $rows->[0] : undef; |
53
|
|
|
|
|
|
|
} |
54
|
|
|
|
|
|
|
|
55
|
|
|
|
|
|
|
sub get_rand_rows_hashref { |
56
|
2
|
|
|
2
|
1
|
3670
|
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__ |