开始从perl中的某一行读取一个大文件

时间:2016-06-24 13:00:57

标签: perl

  1. 我必须匹配2个模式(pattern_1和pattern_2)
  2. 要匹配pattern_2的数据取决于pattern_1(pattern_2使用从pattern_1中提取的一些数据)
  3. pattern_2始终发生在pattern_1
  4. 之后
  5. 一旦完成匹配pattern_2,我需要回到pattern_1匹配的地方并重新开始
  6. 我有以下代码:

    open(DATA_IN, "<$in_file") or die "Couldn't open file $in_file, $!";
    open(DATA_OUT, ">$out_file") or die "Couldn't open file $out_file, $!";
    while(<DATA_IN>){
        if($_ =~ /pattern_1/){
            #extract some data
            open(DATA_TEMP, "<$in_file") or die "Couldn't open file $in_file, $!";
            TEMP: while(<DATA_TEMP>){
                if($_ =~ /pattern_2/){
                    my $i = 0;
                    my $line;
                    while ($i<4){
                        $line = <DATA_TEMP>;
                        $i++;
                    }
                    print $line; #print the data 4 lines after the matched pattern_2
                    last TEMP;
                }
            }
        }
    }
    

    它运行正常,但问题是它每次都会从一开始就加载$ in_file进行pattern_1匹配需要很长时间。 你能建议我一种只从pattern_1开始加载$ in_file的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以使用seek()tell()方法在文件中移动。如下所示:

open(DATA_IN, "<$in_file") or die "Couldn't open file $in_file, $!";
open(DATA_OUT, ">$out_file") or die "Couldn't open file $out_file, $!";
while(<DATA_IN>){
    if($_ =~ /pattern_1/){
        # Save the current position
        my $saved_position = tell(DATA_IN);

        # extract some data
        TEMP: while(<DATA_IN>){
            if($_ =~ /pattern_2/){
                my $i = 0;
                my $line;
                while ($i<4){
                    $line = <DATA_IN>;
                    $i++;
                }
                print $line; #print the data 4 lines after the matched pattern_2
                last TEMP;
            }
        }

        # Restore the saved position
        seek(DATA_IN, saved_position, 0);
    }
}
相关问题