blib/script/stag-flatten.pl untested

filter: Statementstmt 0.0% 0 / 85 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 114 CC 2 SCAR 12.8
CC
2
Cov
0%
setcol
6.0
BEGIN
2.0
BEGIN
2.0
CRAP 3.6
1 #!/usr/local/bin/perl -w
2  
3 # POD docs at end
4  
5 use strict;
6  
7 use Data::Stag qw(:all);
8 use Getopt::Long;
9  
10  
11 my @cols = ();
12 my $sep = "\t";
13 my $parser;
14 my $nest;
15 my $errhandler;
16 my $errf;
17 GetOptions(
18 "parser|format|p=s" => \$parser,
19 "errhandler=s" => \$errhandler,
20 "errf|e=s" => \$errf,
21 "cols|c=s@"=>\@cols,
22 "help|h"=>sub { system("perldoc $0"); exit },
23 "nest|n"=>\$nest,
24 );
25  
26 $errhandler = Data::Stag->getformathandler($errhandler || 'xml');
27 if ($errf) {
28 $errhandler->file($errf);
29 }
30 else {
31 $errhandler->fh(\*STDERR);
32 }
33  
34 my $node = shift;
35 my $fn = shift @ARGV;
36 push(@cols, @ARGV);
37 @cols = map {split/\,/,$_} @cols;
38  
39 my $np = scalar @cols;
40 my %idx = map {$cols[$_]=>$_} (0..$#cols);
41 my @vals = map {[]} @cols;
42 my @level_idx = ();
43  
44 sub setcol {
45 my ($col, $val) = @_;
46 my $i = $idx{$col};
47 die $col unless defined $i;
48 push(@{$vals[$i]}, $val);
49 return;
50 }
51  
52 my %catch = ();
53 foreach my $col (@cols) {
54 $catch{$col} =
55 sub {
56 my ($self, $stag) = @_;
57 setcol($col, $stag->data);
58 return;
59 };
60 }
61 $catch{$node} =
62 sub {
63 my ($self, $stag) = @_;
64 push(@$_, 'NULL') foreach grep {!@$_} @vals; # "left join" - null for non-existent
65
66 if ($nest) {
67 print
68 join("\t", map {'{'.join(', ', @$_).'}'} @vals),
69 "\n";
70 }
71 else {
72 my $c = 1;
73 $c *= scalar(@$_) foreach @vals;
74 if ($c == 1) {
75 # no combinatorial explosion
76 print
77 join("\t", map {$_->[0]} @vals),
78 "\n";
79
80 }
81 elsif ($c == 0) {
82 print STDERR $stag->xml;
83 die "assertion error @vals";
84 }
85 else {
86 # do cartesian explosion
87 #
88 # we COULD do this recursively but it would be slow
89 my @N = map {0} @vals;
90 my $done = 0;
91 while (!$done) {
92 for (my $i=0; $i<@N; $i++) {
93 print "\t" if $i;
94 print $vals[$i]->[$N[$i]];
95 }
96 print "\n";
97 my $i = $#N;
98 my $carry_the_one = 1;
99 while ($i >= 0 && $carry_the_one) {
100 $N[$i] ++;
101 if ($N[$i] >= @{$vals[$i]}) {
102 $N[$i] = 0;
103 $i--;
104 }
105 else {
106 $carry_the_one = 0;
107 }
108 }
109 $done = 1 if $i<0;
110 }
111 }
112 }
113 @vals = map {[]} @cols;
114 return;
115 };
116  
117 my $h = Data::Stag->makehandler(%catch);
118 Data::Stag->parse(-file=>$fn, -format=>$parser, -handler=>$h, -errhandler=>$errhandler);
119 exit 0;
120  
121 __END__