File Coverage

blib/lib/Sort/Sub/by_num_in_text.pm
Criterion Covered Total %
statement 29 35 82.8
branch 13 20 65.0
condition 6 9 66.6
subroutine 6 7 85.7
pod 0 2 0.0
total 54 73 73.9


line stmt bran cond sub pod time code
1             package Sort::Sub::by_num_in_text;
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 2     2   35 use 5.010001;
  2         7  
9 2     2   10 use strict;
  2         4  
  2         39  
10 2     2   9 use warnings;
  2         3  
  2         155  
11              
12             sub meta {
13             return {
14 0     0 0 0 v => 1,
15             summary => 'Sort by first number found in text or (if no number is found) ascibetically',
16             };
17             }
18             sub gen_sorter {
19 2     2 0 6 my ($is_reverse, $is_ci) = @_;
20              
21             sub {
22 2     2   13 no strict 'refs';
  2         3  
  2         553  
23              
24 18     18   30 my $caller = caller();
25 18 50       66 my $a = @_ ? $_[0] : ${"$caller\::a"};
  0         0  
26 18 50       30 my $b = @_ ? $_[1] : ${"$caller\::b"};
  0         0  
27              
28 18         25 my $cmp;
29              
30 18 100       55 my $num_a; $num_a = $1 if $a =~ /(\d+)/;
31 18 100       28 my $num_b; $num_b = $1 if $b =~ /(\d+)/;
  18         47  
32              
33             {
34 18 100 100     26 if (defined $num_a && defined $num_b) {
  18 100 66     71  
    50 33        
35 12         23 $cmp = $num_a <=> $num_b;
36 12 50       21 last if $cmp;
37             } elsif (defined $num_a && !defined $num_b) {
38 2         3 $cmp = -1;
39 2         3 last;
40             } elsif (!defined $num_a && defined $num_b) {
41 4         8 $cmp = 1;
42 4         5 last;
43             }
44              
45 0 0       0 if ($is_ci) {
46 0         0 $cmp = lc($a) cmp lc($b);
47             } else {
48 0         0 $cmp = $a cmp $b;
49             }
50             }
51              
52 18 50       53 $is_reverse ? -1*$cmp : $cmp;
53 2         14 };
54             }
55              
56             1;
57             # ABSTRACT: Sort by first number found in text or (if no number is found) ascibetically
58              
59             __END__