File Coverage

blib/lib/Sort/Sub/by_perl_code.pm
Criterion Covered Total %
statement 41 44 93.1
branch 8 12 66.6
condition n/a
subroutine 12 13 92.3
pod 0 2 0.0
total 61 71 85.9


line stmt bran cond sub pod time code
1             package Sort::Sub::by_perl_code;
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   16 use 5.010;
  1         3  
9 1     1   4 use strict;
  1         1  
  1         16  
10 1     1   4 use warnings;
  1         2  
  1         135  
11              
12             sub meta {
13             return {
14 0     0 0 0 v => 1,
15             summary => 'Sort by Perl code',
16             args => {
17             code => {
18             summary => 'Either compiled code or string code excluding the "sub {" and "}" enclosure',
19             description => <<'_',
20              
21             Code should accept two arguments (the operands to be compared) and is expected
22             to return -1, 0, -1 like the builtin `cmp` operator.
23              
24             _
25             schema => 'str*',
26             req => 1,
27             },
28             },
29             };
30             }
31             sub gen_sorter {
32 6     6 0 12 my ($is_reverse, $is_ci, $args) = @_;
33              
34 6         8 my $code = $args->{code};
35 6 50       13 die "Please supply sorter argument 'code'"
36             unless defined $code;
37              
38 6 100       12 if (ref $code ne 'CODE') {
39 1     1   5 $code = eval "no strict; no warnings; sub { $code }";
  1     1   1  
  1     1   19  
  1     1   3  
  1     1   2  
  1     1   46  
  1         6  
  1         2  
  1         17  
  1         4  
  1         2  
  1         46  
  1         6  
  1         2  
  1         26  
  1         5  
  1         2  
  1         46  
  3         165  
40 3 50       10 die "Can't compile $code: $@" if $@;
41             }
42              
43             sub {
44 1     1   6 no strict 'refs';
  1         1  
  1         137  
45              
46 16     16   23 my $caller = caller();
47 16 50       22 my $a = @_ ? $_[0] : ${"$caller\::a"};
  0         0  
48 16 50       26 my $b = @_ ? $_[1] : ${"$caller\::b"};
  0         0  
49              
50 16         141 my $cmp = $code->($a, $b);
51 16 100       50 $is_reverse ? -1*$cmp : $cmp;
52 6         24 };
53             }
54              
55             1;
56             # ABSTRACT: Sort by Perl code
57              
58             __END__