# input foo bar baz boo foo bar baz bax foo bar baz boo foo bar foo bar baz boo foo bar baz bax foo bar baz boo foo bar baz bax my $max = 40; while(){ chomp; my @elems = split ' '; @elems = grep{ defined $_ }@elems[0..7]; $max -= scalar @elems; last if $max < 0; # exit if printing would make more than 40 elements; print "@elems\n"; last if $. == 6; # exit at 6th line (1+5 more) }