File Coverage

blib/lib/List/Util/sglice.pm
Criterion Covered Total %
statement 35 36 97.2
branch 16 18 88.8
condition n/a
subroutine 4 4 100.0
pod 1 1 100.0
total 56 59 94.9


line stmt bran cond sub pod time code
1             package List::Util::sglice;
2              
3 1     1   69043 use strict;
  1         9  
  1         29  
4 1     1   6 use warnings;
  1         1  
  1         27  
5              
6 1     1   4 use Exporter 'import';
  1         2  
  1         339  
7              
8             our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY
9             our $DATE = '2023-09-18'; # DATE
10             our $DIST = 'List-Util-sglice'; # DIST
11             our $VERSION = '0.001'; # VERSION
12              
13             our @EXPORT_OK = qw(
14             sglice
15             msplice
16             );
17              
18             sub sglice(&\@;$) { ## no critic: Subroutines::ProhibitSubroutinePrototypes
19 6     6 1 6261 my ($code, $array, $num_remove) = @_;
20              
21 6 100       15 $num_remove = @$array unless defined $num_remove;
22              
23 6         10 my @indices;
24 6 100       14 if ($num_remove >= 0) {
25 5         6 for my $index (0 .. $#{$array}) {
  5         15  
26 45 100       149 goto REMOVE if @indices >= $num_remove;
27 44 100       54 if (do { local $_ = $array->[$index]; $code->($_, $index) }) {
  44         57  
  44         73  
28 21         80 push @indices, $index;
29             }
30             }
31             } else {
32 1         3 for my $index (reverse 0 .. $#{$array}) {
  1         3  
33 4 100       30 goto REMOVE if @indices >= -$num_remove;
34 3 100       6 if (do { local $_ = $array->[$index]; $code->($_, $index) }) {
  3         4  
  3         8  
35 2         12 unshift @indices, $index;
36             }
37             }
38             }
39              
40 4 50       14 return unless @indices;
41              
42 6         10 REMOVE:
43             my @removed;
44 6         10 for my $index (reverse @indices) {
45 23         43 unshift @removed, splice(@$array, $index, 1);
46             }
47              
48             RETURN:
49 6         11 my $wantarray = wantarray;
50 6 100       15 if ($wantarray) {
    50          
51 5         38 return @removed;
52             } elsif (defined $wantarray) {
53 1         4 return $removed[-1];
54             } else {
55 0           return;
56             }
57             }
58             1;
59             # ABSTRACT: Remove some elements where code returns true
60              
61             __END__