File Coverage

blib/lib/Algorithm/Graphs/Reachable/Tiny.pm
Criterion Covered Total %
statement 42 43 97.6
branch 18 22 81.8
condition n/a
subroutine 6 6 100.0
pod 1 1 100.0
total 67 72 93.0


line stmt bran cond sub pod time code
1             package Algorithm::Graphs::Reachable::Tiny;
2              
3 2     2   139348 use 5.008;
  2         12  
4 2     2   11 use strict;
  2         4  
  2         60  
5 2     2   11 use warnings;
  2         3  
  2         110  
6              
7 2     2   11 use Carp;
  2         6  
  2         152  
8 2     2   11 use Exporter 'import';
  2         3  
  2         830  
9              
10             our $VERSION = '0.11';
11              
12             our @EXPORT_OK = qw(all_reachable);
13              
14              
15             sub all_reachable {
16 36 50   36 1 241155 @_ == 2 or croak("Need exactly two arguments!");
17 36         52 my ($graph, $nodes) = @_;
18 36 100       86 my %visited = ref($nodes) eq "ARRAY" ? map {$_ => undef} @{$nodes} : %{$nodes};
  30         78  
  18         35  
  18         47  
19 36 100       103 return {} unless %visited;
20 26         58 my @queue = keys(%visited);
21 26 100       61 if (ref($graph) eq 'HASH') {
    50          
22 10 50       13 return \%visited unless %{$graph};
  10         22  
23 10         23 while (defined(my $v = shift(@queue))) {
24 62 100       123 if (exists($graph->{$v})) { ## we need this if() to avoid autovivification!
25 40         75 foreach my $s (keys(%{$graph->{$v}})) {
  40         84  
26 50 100       94 if (!exists($visited{$s})) {
27 42         91 $visited{$s} = undef;
28 42         118 push(@queue, $s);
29             }
30             }
31             }
32             }
33             }
34             elsif (ref($graph) eq 'ARRAY') {
35 16 50       17 return \%visited unless @{$graph};
  16         29  
36 16         40 while (defined(my $v = shift(@queue))) {
37 124 100       201 if (defined($graph->[$v])) {
38 92         99 foreach my $s (keys(%{$graph->[$v]})) {
  92         148  
39 100 100       150 if (!exists($visited{$s})) {
40 84         109 $visited{$s} = undef;
41 84         149 push(@queue, $s);
42             }
43             }
44             }
45             }
46             } else {
47 0         0 croak("Arg 1 must be an ARRAY or HASH reference");
48             }
49 26         118 return \%visited;
50             }
51              
52              
53              
54              
55             1; # End of Algorithm::Graphs::Reachable::Tiny
56              
57              
58             __END__