blib/lib/File/Random/Pick.pm

filter: Statementstmt 45.4% 15 / 33 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 80.0% 4 / 5 Podpod 100% 1 / 1 totaltotal 33.3% 20 / 60 CC 11 SCAR 45.8
CC
11
Cov
28%
random_line
132.0
BEGIN
1.0
BEGIN
1.0
CRAP 97.1
↑ Summary
1 package File::Random::Pick;
2  
3 1 our $DATE = '2019-09-15'; # DATE
4 1 our $VERSION = '0.03'; # VERSION
5  
6 1 ▶use 5.010001;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 our @EXPORT_OK = qw(random_line);
12  
13 0 ▶sub random_line {
Subroutine random_line: not called CC=11 SCAR=48.8
Pod documented
14 0 my ($path, $num_lines) = @_;
15  
16 0 ▶ $num_lines //= 1;
Condition0%0/2
$num_lines //= 1
l!l
00
MC/DC0%0/1
$num_lines //= 1
$num_lines
Truth table0%0/2
A
A= $num_lines
Aresult
11
00
17  
18 0 my $fh;
19 0 ▶ if (ref($path)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $path) { } 0 0 0
20 0 $fh = $path;
21 } else {
22 0 ▶ open $fh, "<", $path or die "Can't open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<", $path or die "Can't open ${path}: $!" 0 0 0
23 }
24  
25 0 ▶ if ($num_lines < 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($num_lines < 1) { } 0 0 0
elsif ($num_lines == 1) { } 0 0 0
26 0 die "Please specify a positive number of lines to pick";
27 } elsif ($num_lines == 1) {
28 # use algorithm from Learning Perl
29 0 my $line;
30 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
31 0 ▶ $line = $_ if rand($.) < 1;
Branch: 1 branch
BranchTrueFalseTotal
if rand $. < 1 0 0 0
32 }
33 0 return $line;
34 } else {
35 0 my @lines;
36 0 ▶ while (<$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $fh)) 0 0 0
37 0 ▶ if (@lines < $num_lines) {
Branch: 1 branch
BranchTrueFalseTotal
if (@lines < $num_lines) { } 0 0 0
38 # we haven't reached $num_lines, put line to result in a random
39 # position
40 0 splice @lines, rand(@lines+1), 0, $_;
41 } else {
42 # we have reached $nnum_items, just replace an item randomly,
43 # using algorithm from Learning Perl, slightly modified
44 0 ▶ rand($.) < @lines and splice @lines, rand(@lines), 1, $_;
Branch: 1 branch
BranchTrueFalseTotal
rand $. < @lines and splice @lines, rand @lines, 1, $_ 0 0 0
45 }
46 }
47 0 return @lines;
48 }
49 }
50  
51 1 1;
52 # ABSTRACT: Pick random lines from a file, without duplicates
53  
54 __END__
↑ Summary