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

In reply to Re: 'rewinding' file to get value from previous line in file? by Not_a_Number
in thread 'rewinding' file to get value from previous line in file? by Angharad

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.