in reply to Re: reading 100 line at a one time
in thread reading 100 line at a one time

Ok,
i have the problem thet i want to read 1000(suppose) at a time instead of reading one line at a time from the log file. and then i will use this block for parsing. is there any code u can provide . i am using following code:

open(handle, "c:\\file.log"); while(<handle>) { #here i use regular expression for parsing line #here i print parse information } now i want it as follow function(filepath, numberofline)#return number of line while(<return line>) { #here i use regular expression for parsing line #here i print parse information }
Is there any solution for it.
its very urgent for me.

Edit by BazB. Add code tags. Remove excess br tags.

Replies are listed 'Best First'.
Re: reading 100 line at a one time
by chromatic (Archbishop) on Mar 01, 2005 at 08:05 UTC

    Whenever you want to repeat something a given number of times, use a loop. For example, in this case the function to read n lines from a filehandle could be:

    sub read_n_lines { my ($fh, $count) = @_; my $buffer; $buffer .= $_ for 1 .. $count; return $buffer; }

    Use it something like:

    open(my $handle, 'c:/file.log') or die "Can't read file: $!\n"; while(not eof( $handle )) { my $chunk = read_n_lines( $handle, 100 ); my $parsed = parse_chunk( $chunk ); print_parsed( $parsed ); }

    You might need a little more logic in read_n_lines() to check for eof, but if you look at the documentation and play around a little bit, you'll figure it out.

Re: reading 100 line at a one time
by jZed (Prior) on Mar 01, 2005 at 08:04 UTC
    The special symbol $. contains the line number of the file you are reading. If you only want the frist 1000 lines, put "last if $. > 1000 just after the start of the while loop. If you want a group from the middle or end just keep track of $. and only start using the lines when you get to where you want to start. If you want the last 1000 lines in the file and it's a big file, you probably should use File::Tail