File Coverage

blib/lib/Sort/Sub/by_count.pm
Criterion Covered Total %
statement 32 36 88.8
branch 8 18 44.4
condition 1 3 33.3
subroutine 7 8 87.5
pod 0 2 0.0
total 48 67 71.6


line stmt bran cond sub pod time code
1             package Sort::Sub::by_count;
2              
3             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
4             our $DATE = '2020-02-28'; # DATE
5             our $DIST = 'Sort-Sub'; # DIST
6             our $VERSION = '0.118'; # VERSION
7              
8 1     1   21 use 5.010001;
  1         3  
9 1     1   6 use strict;
  1         1  
  1         23  
10 1     1   5 use warnings;
  1         1  
  1         275  
11              
12             sub meta {
13             return {
14 0     0 0 0 v => 1,
15             summary => 'Sort by number of occurrences of pattern in string',
16             };
17             }
18              
19             sub _pattern_to_re {
20 1     1   2 my $args = shift;
21              
22 1         2 my $re;
23 1 50       1 my $pattern = $args->{pattern}; defined $pattern or die "Please specify pattern";
  1         3  
24 1 50       3 if ($args->{fixed_string}) {
25 0 0       0 $re = $args->{ignore_case} ? qr/\Q$pattern/i : qr/\Q$pattern/;
26             } else {
27 1 50       2 eval { $re = $args->{ignore_case} ? qr/$pattern/i : qr/$pattern/ };
  1         15  
28 1 50       4 die "Invalid pattern: $@" if $@;
29             }
30              
31 1         2 $re;
32             }
33              
34             sub gen_sorter {
35 1     1 0 3 my ($is_reverse, $is_ci, $args) = @_;
36              
37 1 50       5 die __PACKAGE__.": Please specify 'pattern'" unless defined $args->{pattern};
38              
39 1         2 my $re = _pattern_to_re($args);
40              
41             sub {
42 1     1   7 no strict 'refs';
  1         2  
  1         193  
43              
44 4     4   8 my $caller = caller();
45 4 50       8 my $a = @_ ? $_[0] : ${"$caller\::a"};
  0         0  
46 4 50       9 my $b = @_ ? $_[1] : ${"$caller\::b"};
  0         0  
47              
48 4         5 my $count_a = 0; $count_a++ while $a =~ /$re/g;
  4         28  
49 4         7 my $count_b = 0; $count_b++ while $b =~ /$re/g;
  4         19  
50              
51 4 50 33     21 ($is_reverse ? -1 : 1)*(
52             ($count_a <=> $count_b) ||
53             ($is_ci ? lc($a) cmp lc($b) : $a cmp $b)
54             );
55 1         6 };
56             }
57              
58             1;
59             # ABSTRACT: Sort by number of occurrences of pattern in string
60              
61             __END__