I started with something like almut's state machine but didn't like the way the structure of the file I was trying to read is then encoded into the script structure - feels like poor code/data separation.
What I've ended up with is more like BrowserUk's suggestions. The crucial point (which I didn't really realise when I originally posted) was that the file format defines how many words should be read for each "variable" in the file, although in most cases that length is actually defined by algebra involving previously-read variables. So we can do something like this:
my %v; # this hash holds all the data read # define the names of the "variables" to read from the file # *** in the correct order *** my @varnames = qw/this that theother/; # define where the length to read is not a default my %varlengths = ('that' => 2, 'theother' = '$v{this}*2'} foreach my $var (@varnames){ # get the length to read my $readlength; if(! exists($varlengths{$var}) $readlength = 1; # default } else { $readlength = eval($varlengths{$var}); # compute it } # read into %v if ($readlength == 1){ # read a scalar $v{$var} = unpack TEMPL1, read( $file, $readlength ); } else { # read into an anon. array $v{$var} = [ unpack TEMPL1, read( $file, $readlength ) ]; } }
In reply to Re: Reading binary files - program structure
by Anonymous Monk
in thread Reading binary files - program structure
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |