我有以下代码:
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的方法吗?
答案 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);
}
}