On Wednesday 05 May 2010, Rob Coops wrote:
> Would it not be more efficient to reset the file handle to the star of the
> file?
>
> use strict;
> use warnings;
> use Fcntl qw(:seek);
> ...
> foreach my $condition (@conditions) {
> seek ( $fh, 0, 0 ) or die "ERROR: Could not reset file handle\n";
> while (<LOGFILE>) {
> my $line = $_;
> ...
> }
> }
>
> That way there is not need to re-open the file handle over and over again
> saving on that IO overhead. Of course you need to then deal with the
> posibility of the file being rotated etc. if this is a long running script,
> but if this is a once every now and then started script say once every 5 or
> 10 minutes then you should be fine doing this.
>
> If you want this script to run all the time in a never ending loop and deal
> with rotating files due to size/dates etc, then the reopening of the file is
> the simplest way of doing this.
He may also avoid opening filehandle again by doing this:
eg:-
while ($line = <$fh>)
{
if ($line =~ /$condition1/) { print $fh_out1 "$line"; }
elsif ($line =~ /$condition2/) { print $fh_out1 "$line"; }
}
However, this wouldn't be appropriate if there're more conditions. So the big
question is, which way is better if we need to do a check statement (grep or
regex) with a file multiple times in a program?
1. Storing the file into a list or a variable at the beginning - But what if
the file is huge?
2. Opening filehandles again and again - would cause I/O overhead
3. any other method?
--
Regards,
Akhthar Parvez K
http://Tips.SysAdminGUIDE.COM
UNIX is basically a simple operating system, but you have to be a genius to
understand the simplicity - Dennie Richie