Best way to skip a header when reading in from a t

2019-03-13 10:55发布

I'm grabbing a few columns from a tab delineated file in Perl. The first line of the file is completely different from the other lines, so I'd like to skip that line as fast and efficiently as possible.

This is what I have so far.

my $firstLine = 1;

while (<INFILE>){
    if($firstLine){
        $firstLine = 0;
    }
    else{
        my @columns = split (/\t+/);
        print OUTFILE "$columns[0]\t\t$columns[1]\t$columns[2]\t$columns[3]\t$columns[11]\t$columns[12]\t$columns[15]\t$columns[20]\t$columns[21]\n";
    }
}

Is there a better way to do this, perhaps without $firstLine? OR is there a way to start reading INFILE from line 2 directly?

Thanks in advance!

7条回答
forever°为你锁心
2楼-- · 2019-03-13 11:57

I always use $. (current line number) to achieve this:

#!/usr/bin/perl
use strict;
use warnings;

open my $fh, '<', 'myfile.txt' or die "$!\n";

while (<$fh>) {
    next if $. < 2; # Skip first line

    # Do stuff with subsequent lines
}
查看更多
登录 后发表回答