On Fri, Oct 25, 2013 at 05:14:23PM -0700, Jim Gibson wrote:
> 
> On Oct 25, 2013, at 4:46 PM, Shaji Kalidasan wrote:
> 
> > Dear Perlers,
> > 
> > I am trying to print the matching lines using __DATA__ filehandle and for 
> > the very first time it prints the desired lines, but as soon as I rewind it 
> > using seek, it is printing lines from the very beginning which is not the 
> > desired result (as it prints from the start). I want to rewind only the 
> > __DATA__ part.
> 
> As you have discovered, the special file handle DATA is opened to the source 
> file for your program. When the compiler encounters either of the following 
> lines in your source file:
> 
> __END__
> __DATA__
> 
> 
> it stops reading the source file and leaves the file handle open at that 
> point. The first time you read the <DATA> file handle, you get the line after 
> the '__DATA__' line. But when you rewind the file handle, it is positioned at 
> the beginning of the file, and you get to read your program.
> 
> You have two choices (at least):
> 
> 1. Save the position of the file handle when you enter the program:
> 
>   my $data_pos = tell(<DATA>);
> 
> Then reposition the file to this point instead of at the beginning of the 
> file:
> 
>   seek( DATA, $data_pos, 0 );
> 
> 
> 2. After rewinding the file to the beginning with seek(DATA,0,0), read the 
> file until you encounter the '__DATA__' line. Then start reading the data 
> lines.

The first choice is the correct one.

Ideally, you should use the SEEK_SET constant from Fcntl.  perldoc Fcntl
for details.

And for your third approach, you need C< $. = 0; >

-- 
Paul Johnson - p...@pjcj.net
http://www.pjcj.net

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to