0%

perl 读取文本文件 跳过开头1行或几行 (perl read file skip first line or a few lines)

一直在想办法,如何在perl读取文本文件时,跳过第一行(采用更好的方法)。上网搜了搜,发现有不少人回答类似的问题,但是方法都不尽如人意。
现将网上的一些常见方法罗列下(虽然还有其它写法,但是它们在本质上都是一些)。
比如说,

1
2
3
4
5
open( FH, $yourfile ) or die "Can't open $yourfile: $!\n";
while( <FH> ){
next if /pattern_indicating_line_to_skip/;
# otherwise, do stuff...
}
1
2
3
4
5
6
7
8
9
open FILE, $somefile;
foreach (<FILE>)
{
if (/some_regex/)
{
$want_the_next_line = <FILE>;
$want_the_next_line_after_that = <FILE>;
}
}
1
2
3
4
5
6
7
$line = 0;
while(<IN>) {
if ($line <= N) {
} else {
do something
}
}

以上方法虽然都正确,但是细心的你一定发现了问题。假如我的文本有 1万 行,如果仅仅是为了跳过开头的1行,就在循环中加入了 if 条件,那么余下的 9999 行代码岂不是都白白的进行了无用的比较?

有没有更好的办法呢?

其实办法很简单,只是都被我们忽略了。当我再次google时,在一篇文章中得到了答案。我觉得这个办法挺好的。不知道大家有没有什么其它意见或有更好的办法,欢迎大家回复你的最佳答案。 哈哈哈

1
2
3
4
5
6
7
8
9
open( READ, "<$file" );
readline READ; # skip the first line
while (<READ>) {
my ( $id, $axis1, $axis2, $axis3, $value ) = split /\t/;
$line = sprintf ( "%d\t%d\t%d\t%d\t%d\t%d\n",
$id, $axis1, $axis2, $axis3, $value, $axis1 + $axis2 );
print WRITE $line;
}
close READ;
坚持原创及高品质技术分享,您的支持将鼓励我继续创作!