demo.pl untested

filter: Statementstmt 0.0% 0 / 67 Branchbran 0.0% 0 / 4 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 88 CC 2 SCAR 10.0
CC
2
Cov
0%
new
6.0
add
2.0
children
2.0
CRAP 2.7
1 #!/usr/bin/perl
2  
3 use strict;
4 use warnings;
5 use Carp;
6  
7 # we define our trees
8 package MyTree;
9  
10 use overload '""' => sub {
11 my $self = shift;
12 my $tag = $self->{tag};
13 my @children = @{ $self->{children} };
14 return "<$tag/>" unless @children;
15 local $" = '';
16 "<$tag>@children</$tag>";
17 };
18  
19 sub new {
20 my ( $class, %opts ) = @_;
21 die 'tag required' unless $opts{tag};
22 bless { tag => $opts{tag}, children => $opts{children} // [] }, $class;
23 }
24  
25 sub add {
26 my ( $self, @children ) = @_;
27 push @{ $self->{children} }, $_ for @children;
28 }
29  
30 # teach TPath::Forester how to get the information it needs
31 package MyForester;
32 use Moose;
33 use MooseX::MethodAttributes; # needed for @tag attribute below
34 with 'TPath::Forester';
35  
36 # implement required methods
37  
38 sub children {
39 my ( $self, $n ) = @_;
40 @{ $n->{children} };
41 }
42  
43 sub tag : Attr { # also an attribute!
44 my ( $self, $ctx ) = @_;
45 $ctx->n->{tag};
46 }
47  
48 package main;
49  
50 # make the tree
51 # a
52 # /|\
53 # / | \
54 # b c \
55 # /\ | d
56 # e f | /|\
57 # h / | \
58 # /| i j \
59 # l | | |\ \
60 # m n o p \
61 # /| /|\ \
62 # s t u v w k
63 # / \
64 # q r
65 # / \
66 # x y
67 # |
68 # z
69 my %nodes = map { $_ => MyTree->new( tag => $_ ) } 'a' .. 'z';
70 $nodes{a}->add($_) for @nodes{qw(b c d)};
71 $nodes{b}->add($_) for @nodes{qw(e f)};
72 $nodes{c}->add( $nodes{h} );
73 $nodes{d}->add($_) for @nodes{qw(i j k)};
74 $nodes{h}->add($_) for @nodes{qw(l m)};
75 $nodes{i}->add( $nodes{n} );
76 $nodes{j}->add($_) for @nodes{qw(o p)};
77 $nodes{k}->add($_) for @nodes{qw(q r)};
78 $nodes{m}->add($_) for @nodes{qw(s t)};
79 $nodes{p}->add($_) for @nodes{qw(u v w)};
80 $nodes{r}->add($_) for @nodes{qw(x y)};
81 $nodes{y}->add( $nodes{z} );
82 my $root = $nodes{a};
83  
84 # make our forester
85 my $rhood = MyForester->new;
86  
87 # index our tree (not necessary, but efficient)
88 my $index = $rhood->index($root);
89  
90 # try out some paths
91 my @nodes = $rhood->path('//r')->select( $root, $index );
92 print scalar @nodes, "\n"; # 1
93 print $nodes[0], "\n"; # <r><x/><y><z/></y></r>
94 print $_
95 for $rhood->path('leaf::*[@tag > "o"]')->select( $root, $index )
96 ; # <s/><t/><u/><v/><w/><q/><x/><z/>
97 print "\n";
98 print $_->{tag}
99 for $rhood->path('//*[@tsize = 3]')->select( $root, $index ); # bm
100 print "\n";
101 @nodes = $rhood->path('/>~[bh-z]~')->select( $root, $index );
102 print $_->{tag} for @nodes; # bhijk
103 print "\n";
104  
105 # we can map nodes back to their parents
106 @nodes = $rhood->path('//*[parent::~[adr]~]')->select( $root, $index );
107 print $_->{tag} for @nodes; # bcijxykd
108 print "\n";