`
yhz61010
  • 浏览: 550573 次
  • 来自: -
博客专栏
63c13ecc-ef01-31cf-984e-de461c7dfde8
libgdx 游戏开发
浏览量:11951
社区版块
存档分类
最新评论

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

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

open( FH, $yourfile ) or die "Can't open $yourfile: $!\n";
while( <FH> ){
  next if /pattern_indicating_line_to_skip/;
  # otherwise, do stuff...
}


open FILE, $somefile;
foreach (<FILE>)
{
   if (/some_regex/)
   {
      $want_the_next_line = <FILE>;
      $want_the_next_line_after_that = <FILE>;
   }
}


$line = 0;
while(<IN>) {
    if ($line <= N) {
    } else {
        do something
    }
}


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

    有没有更好的办法呢?

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

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;
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics