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   69931 use 5.008;
  2         12  
4 2     2   11 use strict;
  2         12  
  2         43  
5 2     2   10 use warnings;
  2         6  
  2         86  
6            
7 2     2   14 use Carp;
  2         3  
  2         168  
8 2     2   12 use Exporter 'import';
  2         4  
  2         782  
9            
10             our $VERSION = '0.06';
11            
12             our @EXPORT_OK = qw(all_reachable);
13            
14            
15             sub all_reachable {
16 36 50   36 1 2787 @_ == 2 or croak("Need exactly two arguments!");
17 36         73 my ($graph, $nodes) = @_;
18 36 100       104 my %visited = ref($nodes) eq "ARRAY" ? map {$_ => undef} @{$nodes} : %{$nodes};
  30         107  
  18         40  
  18         64  
19 36 100       126 return {} unless %visited;
20 26         77 my @queue = keys(%visited);
21 26 100       73 if (ref($graph) eq 'HASH') {
    50          
22 10 50       14 return \%visited unless %{$graph};
  10         22  
23 10         30 while (defined(my $v = shift(@queue))) {
24 62 100       148 if (exists($graph->{$v})) { ## we need this if() to avoid autovivification!
25 40         56 foreach my $s (keys(%{$graph->{$v}})) {
  40         85  
26 50 100       96 if (!exists($visited{$s})) {
27 42         73 $visited{$s} = undef;
28 42         108 push(@queue, $s);
29             }
30             }
31             }
32             }
33             }
34             elsif (ref($graph) eq 'ARRAY') {
35 16 50       20 return \%visited unless @{$graph};
  16         43  
36 16         48 while (defined(my $v = shift(@queue))) {
37 124 100       281 if (defined($graph->[$v])) {
38 92         124 foreach my $s (keys(%{$graph->[$v]})) {
  92         196  
39 100 100       203 if (!exists($visited{$s})) {
40 84         152 $visited{$s} = undef;
41 84         221 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         133 return \%visited;
50             }
51            
52            
53            
54            
55             1; # End of Algorithm::Graphs::Reachable::Tiny
56            
57            
58             __END__