chrishowe has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
I am trying to open multiple files at the same time, with the aim of working through a file opening another file halfway through reading the first file, reading the second file, and then jumping back to the original file. Something like reading a webpage, following a link, reading the linked page, and then going back to the original page where you left off.
My skeleton code is below, but it doesn't work. It opens the two files but will only read the second file and not the first one. I know it is something to do with the filehandles going wrong, but I don't know what to do to correct it!
use strict; my @filestack; my $datafile = "text1.txt"; my $handle; my $i = 0; my @raw_data; open ($handle, $datafile); push (@filestack, $handle); $datafile = "text2.txt"; open ($handle, $datafile); push (@filestack, $handle); foreach my $file(@filestack){ print "$i\n"; @raw_data=<$file>; foreach my $temp(@raw_data){ print "$temp\n"; }; close($file); $i++; };
Any help would be appreciated :-)
Cheers!

Replies are listed 'Best First'.
Re: Opening multiple files simultaneously
by kyle (Abbot) on Mar 31, 2009 at 14:36 UTC

    The "open $scalar" idiom takes an undefined scalar and gives it a value. That value is a particular filehandle. If you then open the same filehandle again, it closes the old file.

    Try this.

    sub open_new { my ( $filename ) = @_; open my $fh, '<', $filename or die "Can't read '$filename': $!"; return $fh; } push @filestack, open_new( 'test1.txt' ); push @filestack, open_new( 'test2.txt' );

    Inside open_new, there's a new $fh containing undef every time.

      Superb, cheers :-)