G'day babysFirstPerl,

Welcome to the Monastery.

I'd use the following steps:

  1. Open the file once.
  2. Read through all the headers and capture the file position (tell).
  3. Read the remaining lines and calculate the last data line (based on total lines in file and known number of footer lines).
  4. Reposition the file pointer to the start of the data (seek) and reset the line counter ($.).
  5. Read just the data lines and process as required.
  6. Close the file once.

Here's my test code (pm_1139175_skip_head_and_foot.pl):

#!/usr/bin/env perl use strict; use warnings; use autodie; my $file = 'pm_1139175_skip_head_and_foot.txt'; my ($headers, $footers) = (2, 3); open my $fh, '<', $file; <$fh> for 1 .. $headers; my $last_head_pos = tell $fh; 1 while <$fh>; my $last_data_line = $. - $footers; seek $fh, $last_head_pos, 0; $. = $headers; while (<$fh>) { last if $. > $last_data_line; print; } close $fh;

Given this input:

$ cat pm_1139175_skip_head_and_foot.txt head1 head2 data1 data2 data3 data4 foot1 foot2 foot3

That script produces:

$ pm_1139175_skip_head_and_foot.pl data1 data2 data3 data4

— Ken


In reply to Re: More efficient way to exclude footers by kcott
in thread More efficient way to exclude footers by babysFirstPerl

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.