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   72478 use strict;
  1         12  
  1         31  
4 1     1   6 use warnings;
  1         1  
  1         26  
5              
6 1     1   5 use Exporter 'import';
  1         2  
  1         373  
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.002'; # VERSION
12              
13             our @EXPORT_OK = qw(
14             sglice
15             msplice
16             );
17              
18             sub sglice(&\@;$) { ## no critic: Subroutines::ProhibitSubroutinePrototypes
19 6     6 1 8323 my ($code, $array, $num_remove) = @_;
20              
21 6 100       20 $num_remove = @$array unless defined $num_remove;
22              
23 6         11 my @indices;
24 6 100       17 if ($num_remove >= 0) {
25 5         11 for my $index (0 .. $#{$array}) {
  5         16  
26 45 100       169 goto REMOVE if @indices >= $num_remove;
27 44 100       53 if (do { local $_ = $array->[$index]; $code->($_, $index) }) {
  44         62  
  44         78  
28 21         82 push @indices, $index;
29             }
30             }
31             } else {
32 1         2 for my $index (reverse 0 .. $#{$array}) {
  1         3  
33 4 100       34 goto REMOVE if @indices >= -$num_remove;
34 3 100       4 if (do { local $_ = $array->[$index]; $code->($_, $index) }) {
  3         6  
  3         8  
35 2         11 unshift @indices, $index;
36             }
37             }
38             }
39              
40 4 50       15 return unless @indices;
41              
42 6         9 REMOVE:
43             my @removed;
44 6         12 for my $index (reverse @indices) {
45 23         44 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         44 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__