blib/lib/Perlmazing/Perlmazing/dir.pm untested

filter: Statementstmt 0.0% 0 / 53 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 104 CC 16 SCAR 42.9
CC
16
Cov
0%
_dir
90.0
main
72.0
BEGIN
2.0
CRAP 73.2
1 use Perlmazing qw(croak carp isa_code numeric);
2 use File::Spec;
3  
4 sub main {
5 my ($path, $recursive, $callback);
6 my $usage = 'Usage: dir ($path, $boolean_recursive, $coderef_callback)';
7 my @coderefs = grep { isa_code $_ } @_;
8 my @args = grep { not isa_code $_ } @_;
9 croak "More than one coderef received in arguments, don't know which one to use as callback - $usage" if @coderefs > 1;
10 croak "Too many non coderef arguments received - $usage" if @args > 2;
11 my $wantarray = wantarray;
12 $callback = shift @coderefs;
13 ($path, $recursive) = ('.', 0);
14 @_ = @args;
15 if (@_ == 1) {
16 if (-d $_[0]) {
17 $path = $_[0];
18 } else {
19 croak "The provided path is not a directory or cannot be read";
20 }
21 } elsif (@_ == 2) {
22 if (defined($_[0]) and -d $_[0]) {
23 $path = $_[0];
24 $recursive = $_[1];
25 } elsif (defined($_[1]) and -d $_[1]) {
26 $path = $_[1];
27 $recursive = $_[0];
28 } else {
29 croak "None of your parameters seems to be a valid/readable path";
30 }
31 }
32 $path = File::Spec->catdir(File::Spec->splitdir($path));
33 _dir($path, $recursive, $callback, $wantarray);
34 }
35  
36 sub _dir {
37 my ($path, $recursive, $callback, $wantarray) = @_;
38 if (opendir my $d, $path) {
39 my (@folders, @files, @results);
40 my $process = sub {
41 my $i = shift;
42 $callback->($i) if $callback;
43 push (@results, $i) if $wantarray;
44 };
45 for my $i (sort numeric readdir $d) {
46 my $item = File::Spec->catdir($path, $i);
47 if (-d $item) {
48 next if $i eq '.' or $i eq '..';
49 push @folders, $item;
50 } else {
51 push @files, $item;
52 }
53 }
54 for my $i (@folders) {
55 $process->($i);
56 if ($recursive) {
57 my @r = _dir($i, $recursive, $callback, $wantarray);
58 push (@results, @r) if $wantarray;
59 }
60 }
61 for my $i (@files) {
62 $process->($i);
63 }
64
65 return @results if $wantarray
66 } else {
67 carp "Cannot read path $path: $!";
68 }
69 return;
70 }
71  
72 1;