1 package Parse::Binary::Nested;
11 my ($class, $format) = @_;
12 ref $format eq 'ARRAY'
13 or croak "Invalid Parse::Binary::Nested format: should be an array ref";
14 bless $format, $class;
18 my ($self, $format) = @_;
19 # total (flattened) unpack template from nested format definitions
21 my $value = $format->[-($_ << 1) - 1];
22 if (ref $value eq 'ARRAY') {
23 my $count = $value->[0];
24 $value = $self->template($value);
25 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
26 : $count."X[$count]$count/($value)";
29 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
32 } reverse 0 .. ($#$format - 1) >> 1;
36 my ($self, $format, $data) = @_;
37 # map flat results into a named and nested hash
39 while (my ($field, $template) = splice @$format, 0, 2) {
40 if (ref $template eq 'ARRAY') {
41 my ($count, @subformat) = @$template;
42 my $max = $count =~ s/^(\d+)// ? $1 : 0;
43 $count = !$count ? $max
44 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
45 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
46 splice @{ $res{$field} }, $count if $max > $count;
47 $res{$field} = $res{$field}->[0] if $max == 1;
50 elsif ($template =~ /^Ca/) {
51 $data->[0] = unpack 'C/a', $data->[0];
53 elsif ($template =~ /^(?:[xX]\d*)*$/) {
56 $res{$field} = shift @$data;
62 my ($self, $input) = @_;
63 my @data = unpack $self->template($self), $input;
64 return $self->convert([@$self], \@data);
71 Parse::Binary::Nested - Structured unpack
75 use Parse::Binary::Nested;
76 my $parser = Parser::Binary::Nested->new([
85 my $data = $parser->unpackf("\1foo\0.rest");
86 print $data->{foos}->[0]->{message};
92 Mischa POSLAWSKY <perl@shiar.org>