Thanks Shawn - 'seek' was precisely what I was looking for....

Thanks Telemachus - For the sweet explanation....

And yes David you have made a very valid suggestion. Thanks for that. Will
definitely keep in mind...

Cheers,
Parag




On Tue, Nov 17, 2009 at 11:57 PM, Telemachus <telemac...@arpinum.org> wrote:

> On Tue Nov 17 2009 @ 11:23, Parag Kalra wrote:
> > Now if want to again the loop through the contents of the file I was not
> > able to do the following again:
> >
> > while ( <FILE> ) {
> >     print "$_\n";
> > }
> >
> > Instead I had to first close the previous file handler  and the again
> open
> > the file to loop through the file i.e few more following steps:
> >
> > close FILE;
> >
> > open FILE, "my_file.out";
> > while ( <FILE> ) {
> >     print "$_"."----"."$_\n";
> > }
> > close FILE;
> >
> > Can't this again closing and opening of file avoided while looping
> through
> > the file?
>
> Part of what happens when you go through a file line by line using readline
> (in your code <> is simply a prettier way of writing readline) is that Perl
> keeps track of where you are in the file. That way, successive calls get
> successive lines. Once you've gone through the whole file, you're at the
> end, so you can't simply pick up and read again.
>
> However, you can use the function seek to reset the pointer to the top of
> the file:
>
>        seek(FILE, 0, 0)
>
> See perldoc -f seek.
>
> While we're not on the subject, you shouldn't be using bareword
> filehandles like FILE, but you *should* always check that the file opened
> properly. See the documentation for open for how to use lexical
> filehandles, but it would look something like this:
>
>        open my $fh, '<', 'my_file.in'
>                or die "Can't open 'my_file.in' for reading: $!";
>        while (<$fh>) {
>                # do stuff to the line
>        }
>
> See perldoc -f open and perldoc perlopentut for more.
>
> (You're also overquoting. I think someone mentioned it to you, but I'll
> throw in my two cents there too.)
>
> --
> 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