--- Kevin Old <[EMAIL PROTECTED]> wrote:
> Hello all,
> 
> I know this has been asked a few times over the years, but I can't find
> an answer that is what I need in the archives.
> 
> I have 2 files. I have a for loop.  I need to read from both files with
> 1 file handle, or whatever will allow my code to read from both files
> alternating between them.

Kevin,

I'm sure there is a module for this somewhere, but I don't know it offhand (and a 
quick search
didn't reveal it).  You did mention that you wanted the files handles to be finished 
at roughly
the same time, but I'm not sure exactly what you meant by that.  I wrote a small test 
program that
takes a list of files, opens them, and reads each file sequentially allowing you to 
process all
lines.  

If one file has fifteen lines and another file has three lines then you will be 
processing the
extra 12 lines from the first file *after* the three lines from the second file.  It 
should be
noted that this program doesn't tell you which file is which as you didn't necessarily 
specify
that in your email.  It should be fairly easy to add, though.

Cheers,
Ovid

#!/usr/bin/perl -w
use strict;
use IO::File;
use vars qw( @file_handle $open_files );

my @files = qw( file1 file2 bad_file );
while( my @lines = read_data( \@files ) ) {
    foreach my $lines ( @lines ) {
        print $lines;
    }
}

sub read_data {
    my $files = shift;
    unless ( defined $open_files ) {
        initialize_file_handles( $files );
    }
    my (@lines,@finished_files);
    return unless $open_files;
    foreach my $index ( 0 .. $#file_handle ) {
        my ($name,$fh) = @{ $file_handle[$index] };
        if ( my $line = <$fh> ) {
            push @lines => $line;
        }
        else {
            push @finished_files => $index;
        }
    }
    foreach my $index ( @finished_files ) {
        close  $file_handle[ $index ][1];
        splice @file_handle, $index, 1;
        $open_files--;
    }
    return @lines;
}

sub initialize_file_handles {
    my $files = shift;
    $open_files = 0;

    foreach my $file ( @$files ) {
        my $fh = IO::File->new( "< $file" );
        if ( defined $fh ) {
            $file_handle[ $open_files ] = [ $file, $fh ];
            $open_files++;
        }
        else {
            warn "Could not open $file for reading: $!";
        }
    }
}

=====
"Ovid" on http://www.perlmonks.org/
Someone asked me how to count to 10 in Perl:
push@A,$_ for reverse q.e...q.n.;for(@A){$_=unpack(q|c|,$_);@a=split//;
shift@a;shift@a if $a[$[]eq$[;$_=join q||,@a};print $_,$/for reverse @A

__________________________________________________
Do you Yahoo!?
HotJobs - Search new jobs daily now
http://hotjobs.yahoo.com/

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to