For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > March 2006 > How to directly seek to a particular line number while reading a file in Perl









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author How to directly seek to a particular line number while reading a file in Perl
jeniffer

2006-03-27, 9:59 pm

I want to directly s to a particular line in an opened file and
ensure that the reading of the file starts from there only.The lines in
the file are of random length and so s cannot be used.Presently i am
looping from the start ,maintaining a counter and checking whether
desired line has reached.

Sisyphus

2006-03-28, 4:00 am


"jeniffer" <zenith.of.perfection@gmail.com> wrote in message
..
..
> Presently i am
> looping from the start ,maintaining a counter and checking whether
> desired line has reached.
>


You don't need to maintain a counter. Perl has the special variable called
"$." which does that for you. See 'perldoc perlvar'.

Cheers,
Rob


xhoster@gmail.com

2006-03-28, 7:00 pm

"jeniffer" <zenith.of.perfection@gmail.com> wrote:
> I want to directly s to a particular line in an opened file and
> ensure that the reading of the file starts from there only.The lines in
> the file are of random length and so s cannot be used.Presently i am
> looping from the start ,maintaining a counter and checking whether
> desired line has reached.


So what is the problem with that method? Too slow? Too error prone?
What is your question?

If not worried about portability, I'd probably do this:

open my $fh, "tail +$start_line file | " or die $!
while (<$fh> ) {
#...
};
close $fh or die $!;

Xho

--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
jl_post@hotmail.com

2006-03-28, 7:00 pm

jeniffer wrote:
> I want to directly s to a particular line in an opened file and
> ensure that the reading of the file starts from there only.The lines in
> the file are of random length and so s cannot be used.Presently i am
> looping from the start ,maintaining a counter and checking whether
> desired line has reached.



Dear Jeniffer,

If you want to use a conventional while-loop to loop through the
lines of your file, you can always make use of the $. variable (read
more about it in "perldoc perlvar"). For example, let's say you want
to print out every line in uppercase of the file starting with the
tenth line, you can do something like this:

while (<IN> )
{
next if $. < 10; # skip all lines before the tenth one
print uc($_); # print line in upper-case
}

I hope this helps, Jeniffer.

-- Jean-Luc

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com