in reply to More efficient way to exclude footers

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