in reply to 'rewinding' file to get value from previous line in file?
First and foremost, a quibble:
...the first Z item starts at element 5 and ends at element 89, making it 84 elements in length
By my calculations, that makes it 85 elements long (if it started at 1 and ended at 3, it would be 3 elements long, no? Google for "fencepost error", or, if you really want an answer of 84, adjust my code below accordingly).
That said, here is another approach to your problem (TIMTOWDI) that should also deal with cases where the Z item has been 'mistakenly broken up' into more than two different lines (you don't say that this can happen, but are you sure?).
use strict; use warnings; my ( $length, @lengths ); my $last = 0; while ( <DATA> ) { next unless /Z\s+(\d+)\s+(\d+)/ and $2 >= $1; if ( $1 > $last + 1 ) { push @lengths, $length if $length; $length = $2 - $1 + 1; } else { $length += $2 - $1 + 1; } $last = $2; } push @lengths, $length; print scalar @lengths, " Z items found:\n"; print join "\n", @lengths; __DATA__ Z 1 1 Z 5 89 ~#à^''$%!@ => line noise Z 91 102 Z 103 123 Z 124 150 Z 151 191 Z 500 504 Z 505 509
|
|---|