dwslovedh has asked for the wisdom of the Perl Monks concerning the following question:
Hi there, I want to write a function that can return one record from a file ervery time, for example, the records in input.txt are like this:
_________________________ 12 dd DH: mm struct{ int a; char b; m1 struct { int c; int d; }; m2 struct { int e; int f; }; } 2 dfdkk df dd } 1 LOCAL_PARAM: ssi_struct { ref = 0; header = { req = 0xa; }; } DH: mm struct{ int a; char b; m1 struct { int c; int d; }; } ____________________________________
I want to use a function to extract the records starting with "DH:" each time I call it,like this $record = get_record("input.txt"); So I must remember the position of the file last read, and continue to extract the record. I use the seek and tell, but it didn't work. Here is the script:
sub get_record_from_file { my $filein = shift; my $regex = shift; my $pos = shift open FILEIN, "<$filein" or die "!$\n"; seek(FILEIN, $pos, 0); my $in_block = 0; my $last = "}"; my @array = {}; foreach my $line (<FILEIN>) { if ($line =~ /$regex/) { $in_block = 1; } if ($in_block) { push @array, $line; } if ($line =~ m/$last$/) { $in_block = 0; } } $pos = tell FILEIN; return (\@array, $pos); } $record = get_record_from_file("input.txt","DH:",0);
Can anyone help? Thanks:)
Update
correct some mistakes: Here is the script:
sub get_record_from_file { my $filein = shift; my $regex = shift; my $pos = shift open FILEIN, "<$filein" or die "!$\n"; seek(FILEIN, $pos, 0); my $in_block = 0; my $last = "}"; my @array = {}; foreach my $line (<FILEIN>) { if ($line =~ /$regex/) { $in_block = 1; } if ($in_block) { push @array, $line; } if ($line =~ m/$last$/) { $in_block = 0; last; } } $pos = tell FILEIN; return (\@array, $pos); } my $curpos = 0; ($record,$curpos) = get_record_from_file("input.txt","DH:",$curpos);
The $curpos is not updated. For example, you call the function once, and return the $curpos = 174; next time I call it, $curpos is still 174. Thanks:)
|
---|