in reply to Skipping data on file read

Probably someone will tell you the bug, but that still makes this code hard to read, understand and maintain. Especially the multiple reads from $FILE are errorprone. And it really gets dark when your input file has an error in it.

My suggestion would be to rewrite this code as a state machine. A state machine has one variable with possible values of 0,1,2,3,.... That is the state. Whenever you parse something, for example a line with 'be0.01t' in it, you change the state to reflect where you are in the file. So state 1 might mean "I've just parsed a line with ####.30c, I'm expecting more of them now or blank lines or comments".

You might even draw a simple diagram now with arrows connecting two states, where one can lead to the other and note the condition on the arrow.

The new code would look somewhat like this:

my $state=0; #state 0 you expect a card id or comments while ( my $line = <$FILE> ) { if ($state==0) { if ($line=~/.../) { dosemthing; $state=1; } elsif ($line=~/.../) { dosemthingelse; $state=4; else { print "error in datafile"; $state=0; } } elsif ($state==1) { if ($line=~/.../) { ...
The code will be more wordy but it will be a lot more mantainable and you will be more confident that your program can read whatever is coming at it

Replies are listed 'Best First'.
Re^2: Skipping data on file read
by dragonchild (Archbishop) on Jun 13, 2008 at 02:06 UTC
    There are several state machine frameworks on CPAN, the most notable being POE.

    This is also how parsers and lexers are generally written, if you've had experience with those.


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?