In the spirit of perhaps using a screwdriver to pound a nail (or maybe just putting arbitrary restrictions on yourself...sort of like composing a 12-tone piece), I wanted to see if I could use
RFC: DBIx::Iterator to solve this. The function in the module returns an iterator that returns a hashref, so I wrapped the iterator returned from that to return an array (so this makes an iterator that returns a row of data at a time, so it is not quite what the OP asked for...but you can easily wrap the iterator to do that). Here is what I came up with:
#!/usr/bin/perl
use strict;
use warnings;
use DBIx::Iterator qw(mk_iterator list_iterator);
my $data_struct = [
...snip...(see OP)
];
my $iter = flatten($data_struct);
while ( my @row = $iter->() ) {
print "@row\n";
}
sub flatten {
my $data = shift;
my $iter = mk_iterator(_flatten(0, $data));
sub {
my $data = $iter->() or return;
return @$data{sort { $a <=> $b } keys %$data};
}
}
sub _flatten {
my ($i, $data) = @_;
my @tmp = @$data;
my @groups = ();
while (@tmp) {
my @nxt_group;
push @nxt_group, shift @tmp
while @tmp > 2 and !ref($tmp[1]);
push @nxt_group, @tmp and @tmp=()
if @tmp <= 2 and !grep ref($_), @tmp;
if ( @nxt_group ) {
push @groups, [ mk_list_iter($i, @nxt_group) ];
}
if ( @tmp ) {
my @nxt_grp;
push @nxt_grp, mk_list_iter($i, shift(@tmp));
push @nxt_grp, _flatten($i+1, shift(@tmp))
while @tmp and ref($tmp[0]);
push @groups, [ @nxt_grp ];
}
}
return @groups;
}
sub mk_list_iter {
my ($i, @list) = @_;
sub {
list_iterator(
LIST => [ map { [$_] } @list ],
SELECT => [ $i ],
@_
);
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.